Antarr Byrd
Antarr Byrd

Reputation: 26159

What does "|>" mean in elixir?

I'm reading through some code elixir code on github and I see |> being used often. It does not appear in the list of operation on the documentation site. What does it mean?

i.e.

expires_at:    std["expires_in"] |> expires_at,

Upvotes: 36

Views: 17440

Answers (3)

Onorio Catenacci
Onorio Catenacci

Reputation: 15343

In addition to Stefan's excellent response, you may want to read the section called "Pipeline Operator" of this blog posting for a better understanding of the use case that the pipeline operator is intended to address in Elixir. The important idea is this:

The pipeline operator makes it possible to combine various operations without using intermediate variables. . .The code can easily be followed by reading it from top to bottom. We pass the state through various transformations to get the desired result, each transformation returning some modified version of the state.

Upvotes: 4

Zaal Kavelashvili
Zaal Kavelashvili

Reputation: 558

It gives you ability to avoid bad code like this:

orders = Order.get_orders(current_user)
transactions = Transaction.make_transactions(orders)
payments = Payment.make_payments(transactions, true)

Same code using pipeline operator:

current_user
|> Order.get_orders
|> Transaction.make_transactions
|> Payment.make_payments(true)

Look at Payment.make_payments function, there is a second parameter bool_parameter. The first parameter references the variable that is calling the pipe:

def make_payments(transactions, bool_parameter) do
   //function 
end

When developing Elixir application keep in mind that important parameters should be at first place, in future it will give you ability to use pipeline operator.

I hate this question when writing non elixir code: what should i name this variable? I waste lots of time on answer.

Upvotes: 41

Stefan Hanke
Stefan Hanke

Reputation: 3518

This is the pipe operator. From the linked docs:

This operator introduces the expression on the left-hand side as the first argument to the function call on the right-hand side.

Examples

iex> [1, [2], 3] |> List.flatten()

[1, 2, 3]

The example above is the same as calling List.flatten([1, [2], 3]).

Upvotes: 44

Related Questions