What does “|>” mean in elixir?

2020-05-30 09:23发布

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,

标签: elixir
3条回答
淡お忘
2楼-- · 2020-05-30 09:32

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(transaction, 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 second bool parameter, if that was first parameter like this:

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

it would not worked anymore.

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.

查看更多
smile是对你的礼貌
3楼-- · 2020-05-30 09:35

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]).

查看更多
劳资没心,怎么记你
4楼-- · 2020-05-30 09:44

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.

查看更多
登录 后发表回答