What is the “|>” in Elixir for?

Question:

Reading some codes I see |> being used commonly. What does it mean?

Answer:

The |> symbol is known as the pipe operator . The pipe |> operator is extremely useful and will certainly improve the readability of your code with Elixir.

It basically takes the output of the expression on the left and passes it as the first argument of a function on the right.

Let's say I don't know about the pipe operator and want to multiply all the values ​​in a list by two, then filter out those greater than 4, our code will look like this:

lista = [1, 2 , 3]
Enum.filter(Enum.map(lista, &(&1 * 2)), &(&1 > 4))

If we use the pipe operator, our example will be different:

lista = [1, 2, 3]
# A lista gerada no primeiro map será o primeiro parametro do filter
Enum.map(lista, &(&1 * 2)) |> Enum.filter(&(&1 > 4))

Or, in iex:

[1, 2, 3] |> Enum.map(&(&1 * 2))  |> Enum.filter(&(&1 > 4))

And in a file:

[1, 2, 3] 
|> Enum.map(&(&1 * 2))  
|> Enum.filter(&(&1 > 4))

You can read more about the pipe operator and other language features in the official documentation and elixirschool

Scroll to Top