What is "|>" for in Elixir?

Asked

Viewed 155 times

4

Reading some codes from I see |> be used commonly. What it means?

1 answer

8


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

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

Let’s say I’m not aware of the pipe operator and want to multiply all values of a list by two, then filter those that are greater than 4, our code will be as follows:

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 even, in the iex:

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

And in an archive:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.