Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "|>" mean in elixir?

Tags:

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, 
like image 569
Antarr Byrd Avatar asked Feb 23 '15 04:02

Antarr Byrd


People also ask

What does the pipe operator do in Elixir?

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 a pipe operator?

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.


2 Answers

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

like image 76
Stefan Hanke Avatar answered Oct 04 '22 00:10

Stefan Hanke


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.

like image 22
Zaal Kavelashvili Avatar answered Oct 03 '22 22:10

Zaal Kavelashvili