问题
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,
回答1:
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])
.
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/28666827/what-does-mean-in-elixir