Elixir Language Operators The Pipe Operator

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

The Pipe Operator |> takes the result of an expression on the left and feeds it as the first parameter to a function on the right.

expression |> function

Use the Pipe Operator to chain expressions together and to visually document the flow of a series of functions.

Consider the following:

Oven.bake(Ingredients.Mix([:flour, :cocoa, :sugar, :milk, :eggs, :butter]), :temperature)

In the example, Oven.bake comes before Ingredients.mix, but it is executed last. Also, it may not be obvious that :temperature is a parameter of Oven.bake

Rewriting this example using the Pipe Operator:

[:flour, :cocoa, :sugar, :milk, :eggs, :butter]
|> Ingredients.mix
|> Oven.bake(:temperature)

gives the same result, but the order of execution is clearer. Furthermore, it is clear that :temperature is a parameter to the Oven.bake call.

Note that when using the Pipe Operator, the first parameter for each function is relocated to before the Pipe Operator, and so the function being called appears to have one fewer parameter. For instance:

Enum.each([1, 2, 3], &(&1+1)) # produces [2, 3, 4]

is the same as:

[1, 2, 3]
|> Enum.each(&(&1+1))


Got any Elixir Language Question?