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
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)
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.
Worked examples
A string pipeline, a list pipeline, a call with extra arguments, and the first-argument rule.