“|>”在长生不老药中是什么意思?

What does "|>" mean in elixir?

我正在阅读 github 上的一些代码长生不老药代码,我看到 |> 经常被使用。它没有出现在文档站点的 operation 列表中。这是什么意思?

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

这是pipe operator。来自链接文档:

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

除了 Stefan 的出色回复外,您可能还想阅读此 blog posting 中名为 "Pipeline Operator" 的部分,以便更好地理解管道运算符旨在在 Elixir 中解决的用例.重要的想法是:

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.

它使您能够避免像这样的错误代码:

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

使用管道运算符的相同代码:

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

看Payment.make_payments函数,有第二个bool参数。第一个参数引用调用管道的变量:

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

在开发 elixir 应用程序时,请记住重要参数应放在首位,将来它将使您能够使用管道运算符。

我在编写非长生不老药代码时讨厌这个问题:我应该给这个变量命名什么?我在回答上浪费了很多时间。