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,
The pipe operator is the main operator for function composition in Elixir. It takes the result of the expression before it and passes it as the first argument of the following expression. Pipes replace nested function calls like foo(bar(baz)) with foo |> bar |> baz .
What is the Pipe Operator? The pipe operator is a special operational function available under the magrittr and dplyr package (basically developed under magrittr), which allows us to pass the result of one function/argument to the other one in sequence. It is generally denoted by symbol %>% in R Programming.
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])
.
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. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With