Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 48 ยท Core Language

The Pipe Operator

Learn the Elixir pipe operator |>: how it passes values as the first argument, how to design pipeline-friendly functions, use then and tap, and avoid common traps.

Data processing is usually a chain: take some input, clean it, transform it, format it. Without help, that chain turns into nested calls that you must read from the inside out, or into a ladder of temporary variables. Elixir's pipe operator |> lets you write the steps in the order they happen, from top to bottom.

The pipe is plain syntax sugar, with no runtime cost, and it only works well because Elixir's standard library follows one convention: the main data goes in the first argument. This lesson explains how the pipe works, how to write functions that fit into pipelines, the helpers then/2 and tap/2, and where pipes make code worse. You should know functions and modules first.

Elixir cannot run on this site, so Elixir snippets are read-only. The runnable examples are JavaScript stand-ins that show the same data flow.

From nesting to a pipeline

Here is a task: take a string, trim it, make it lowercase, split it into words, and count them. Written as nested calls:

ELIXIR
length(String.split(String.downcase(String.trim("  Hello Big World  "))))

You have to start at the innermost call and work outwards. With the pipe:

ELIXIR
"  Hello Big World  "
|> String.trim()
|> String.downcase()
|> String.split()
|> length()
# 3

The rule is simple: a |> f(b) is rewritten at compile time to f(a, b). The value on the left becomes the first argument of the call on the right. The parentheses on f() are required, even when there are no other arguments.

What |> does

Left side Any expression produces a value.
Pipe Inserts it as the first argument.
Right side A function call with the rest of the arguments.

x |> f(y) becomes f(x, y) before the code runs.

1 / 2

A pipe stand-in in JavaScript

JavaScript has no pipe operator, but you can build the same thing with a helper. It passes each result into the next function:

JS Pipe as a helper function

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In JavaScript, method chaining already gives you this look for strings and arrays. Elixir has no methods on values, so the pipe plays that role for every function in every module.

Pipelines with extra arguments

Everything that is not the piped value is written as usual in the call:

ELIXIR
[5, 3, 8, 1, 9, 2]
|> Enum.filter(fn n -> n > 2 end)
|> Enum.map(fn n -> n * 10 end)
|> Enum.sort(:desc)
|> Enum.take(3)
# [90, 80, 50]

You can pipe into anonymous functions written with the capture operator, but be careful: |> (fn x -> x + 1 end).() needs the extra parentheses and the dot call, which is why then/2 exists (see below). You can also pipe into any module function you wrote, as long as it takes the data first.

Designing pipeline-friendly functions

The convention to follow is: the thing you are working on goes first. Compare these two signatures for a function that adds a tax rate to a price:

ELIXIR
def add_tax(rate, price), do: price * (1 + rate)   # awkward in a pipeline
def add_tax(price, rate), do: price * (1 + rate)   # pipe friendly

With the second shape, 100 |> add_tax(0.2) reads naturally. A few guidelines:

  • Make the main subject (list, map, struct, string) the first parameter, and options last.
  • Return the same kind of value you accept, so the next step can take it. A function that takes a map and returns a map chains well; one that returns {:ok, map} does not (more on that below).
  • Keep each step small and named by what it does: normalize_email, drop_empty, apply_discount.
  • Put several steps of a struct update in functions that take and return the struct.
ELIXIR
defmodule Cart do
  defstruct items: [], discount: 0

  def new, do: %Cart{}
  def add_item(cart, name, price), do: %{cart | items: [{name, price} | cart.items]}
  def set_discount(cart, percent), do: %{cart | discount: percent}
  def total(cart) do
    sum = cart.items |> Enum.map(&elem(&1, 1)) |> Enum.sum()
    sum * (100 - cart.discount) / 100
  end
end

Cart.new()
|> Cart.add_item("book", 20)
|> Cart.add_item("pen", 5)
|> Cart.set_discount(10)
|> Cart.total()
# 22.5

Each builder function takes the cart first and returns a cart, so they snap together. Because data is immutable, every step returns a new value and the earlier ones are untouched.

JS A pipe-friendly cart in JavaScript

Press Run (or Ctrl + Enter) to see the console output here.

No output.

then/2 and tap/2

Sometimes a step does not take the data first, or you want a side effect without changing the value. Two small functions from Kernel cover this.

then/2 calls a function with the piped value, so you can put it anywhere:

ELIXIR
5
|> then(fn n -> Enum.map(1..3, fn i -> i * n end) end)
# [5, 10, 15]

"[email protected]"
|> String.split("@")
|> then(fn [name, domain] -> %{name: name, domain: domain} end)

tap/2 runs a function for its side effect and then returns the original value untouched. It is perfect for logging or debugging in the middle of a pipeline:

ELIXIR
[3, 1, 2]
|> Enum.sort()
|> tap(fn sorted -> IO.inspect(sorted, label: "after sort") end)
|> Enum.map(&(&1 * 2))
# prints: after sort: [1, 2, 3]
# returns [2, 4, 6]

A shorter debugging tool is IO.inspect/2, which prints the value and returns it, so it can be dropped between any two pipe steps. dbg/2 goes further: when it is the last step of a pipeline it prints every intermediate value.

JS then and tap as helpers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Readability pitfalls

The pipe is easy to overuse. Watch for these cases:

A single call. x |> f() is just a longer way to write f(x). Elixir's formatter keeps it, but readers expect a pipe to have at least two steps. Do not start a pipeline from a function call result with nothing else:

ELIXIR
# unclear
String.trim(input) |> String.upcase()

# better: start with a plain value
input
|> String.trim()
|> String.upcase()

Starting with a function call. Begin pipelines with a variable or literal, so it is visible what the data is.

Mixed return shapes. If a step returns {:ok, value} or {:error, reason}, piping it onward feeds the whole tuple to the next function and crashes or misbehaves. Use with or small pattern-matching functions for fallible steps, and pipe only the happy parts.

Operator precedence. The pipe binds tighter than comparison and boolean operators. So a == b |> f() means a == f(b), not f(a == b). When you mix operators with a pipe, add parentheses to make the grouping obvious.

Too long. Ten steps in one pipeline can be harder to follow than three named functions of three steps. Extract a function when a group of steps has a clear name.

Piping into an anonymous function. value |> fun.() works (note the dot), but prefer then/2 when the function is written inline.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does "abc" |> String.upcase() compile to?

    The pipe inserts the left-hand value as the first argument of the call on the right, so it becomes String.upcase("abc").
  2. 2. Which signature is the most pipeline-friendly?

    The data being transformed should be the first parameter, with options after it, so that cart |> add(5) works.
  3. 3. What does tap/2 return?

    tap runs the function for its side effect (like logging) and then returns the input unchanged, so the pipeline continues with the same value.
  4. 4. Why is piping a function that returns {:ok, value} into the next step usually a bug?

    The pipe passes the entire result along. Unwrap fallible steps with pattern matching or with, then pipe the plain values.

Summary

  • a |> f(b) becomes f(a, b) at compile time; the pipe is free at runtime.
  • The convention that the subject is the first argument is what makes pipelines work. Follow it in your own functions.
  • Always write the parentheses: |> String.trim().
  • then/2 lets you place the value anywhere; tap/2 runs a side effect and keeps the value; IO.inspect/2 and dbg/2 help with debugging.
  • Avoid one-step pipes, pipelines that start with a function call, mixing in {:ok, _} tuples, and long chains with no named pieces.
  • Use parentheses when mixing operators and pipes.

Next: how Elixir repeats work without loops in Recursion and Tail Calls.