jonnifyelixir
F3 / F3.03 / pipe

F3.03 · part 3 of 3

The pipe operator

The pipe operator |> takes the value on its left and passes it as the first argument to the function call on its right. That single rule turns a nest of function calls, read inside-out, into a top-to-bottom pipeline read in the order it runs — the same composition you saw with folds in F2, written as syntax.

The same grade computation, two ways: nested calls versus a pipeline. Both produce :b; one is far easier to read.

Inside-out vs left-to-right

Averaging then grading a score list is two function calls. Nested, the inner call must be read first; piped, the steps read in run order. Select a form — the data flow is identical, only the reading changes.

The form · select one

average grade [80, 92, 74] → 82.0 → :b source reads in run order, left to right

      

form: piped  ·  result: :b

expression: [80, 92, 74] |> Portal.average() |> Portal.grade()

Both forms call average then grade on the same data. The pipe does not change what runs — it changes the order you read it in, from inside-out to the order of execution.

The value goes first

The whole rule is: x |> f(a, b) is rewritten to f(x, a, b) — the piped value becomes the first argument, and any arguments you write are appended after it. That is why Elixir’s core functions take their main subject first (Enum.filter(list, fun), String.split(str, on)): it makes them pipe cleanly. Design your own functions the same way and they slot into a pipeline without wrappers.

# x |> f(a, b)  is  f(x, a, b) — the value is inserted as the first argument
[80, 92, 74]
|> Enum.filter(&(&1 >= 80))   # Enum.filter([80, 92, 74], fun) => [80, 92]
|> Enum.sum()                 # Enum.sum([80, 92])            => 172

# the nested equivalent, read inside-out:
Enum.sum(Enum.filter([80, 92, 74], &(&1 >= 80)))

F3.03.1–2 · functions in modules

Named functions, grouped under a module, taking their subject first.

F3.03.3 · the pipe composes them

|> threads a value through the chain, first argument first.

That completes F3.03: functions are the unit of work, modules are the namespace, and |> is the glue. Next module: F3.04 — Enumerables & streams, where you pipe a whole collection through the Enum toolkit.

References

Primary sources for this lesson, and where it connects in the course.