jonnifyelixir
F2 / F2.08 / pipe

F2.08 · part 2 of 3

The pipe operator

The pipe operator |> takes the value on its left and passes it as the first argument to the call on its right. Chained, it threads a value through a series of functions, written in the order they run — the opposite of reading nested calls from the inside out.

It is purely a rewrite. x |> f() is f(x); x |> f(a) is f(x, a). Nothing is added but clarity: a long f(g(h(x))) becomes a top-to-bottom list of steps. The one thing to keep in mind is that the piped value always lands in the first argument position.

Nested or piped

The nested call square(double(inc(x))) and the pipe x |> inc() |> double() |> square() compute the same value. The nested form reads inside out; the pipe reads in order. Toggle between them.

pipe operator
|> — feeds the left value as the first argument on the right.
first argument
where the piped value lands in the call.
desugar
the plain nested call a pipe is shorthand for.
readability
steps read top to bottom, in execution order.

same value · two ways to write it

2
form square(double(inc(2))) reads inside out: inc first, square last stages 2 → 3 → 6 → 36 36


      
both forms compute ((x+1) × 2)² · nested reads inside out, piped reads in order · 36

Idea

The pipe rearranges the text so reading order matches execution order.

F2.08.1 · compose

This is the same composition, written forwards instead of nested.

Nested and piped are the same computation. The pipe reads in the order the steps run.

Extra arguments

When a piped function takes more arguments, the piped value fills the first slot and the rest follow. x |> f(a) is f(x, a) — never f(a, x). Pick a call and see how it desugars.

x |> f(a) becomes f(x, a)

piped 5 |> Kernel.+(3) becomes Kernel.+(5, 3) result 8


      
5 |> Kernel.+(3) · 5 is the first argument · 8

Idea

The piped value is always the first argument; later arguments are written in the call.

Elixir

The Enum functions take the collection first — built for piping.

Extra arguments follow the piped value, which always takes the first position.