Elixir The Pipe Operator
Data transformations often consist of several steps: trim the input, split it, convert each part, filter, sum. Written as nested calls, the steps read from the inside out. The pipe operator |> lets you write them top to bottom, in the order they happen.
input = " 12, 7, 30, abc, 5 "
# Nested calls: read from the inside out
nested = Enum.sum(Enum.map(Enum.filter(String.split(String.trim(input), ", "), &(&1 =~ ~r/^\d+$/)), &String.to_integer/1))
IO.inspect(nested)
# The same with pipes: read top to bottom
piped =
input
|> String.trim()
|> String.split(", ")
|> Enum.filter(&(&1 =~ ~r/^\d+$/))
|> Enum.map(&String.to_integer/1)
|> Enum.sum()
IO.inspect(piped)54
54
How it works
x |> f(a, b) is rewritten by the compiler to f(x, a, b): the value on the left becomes the first argument of the call on the right. That's all. It is not a special data type or a "chain object".
| Pipe | Same as |
|---|---|
"hi" |> String.upcase() |
String.upcase("hi") |
[3, 1] |> Enum.sort() |
Enum.sort([3, 1]) |
list |> Enum.map(&(&1 + 1)) |
Enum.map(list, &(&1 + 1)) |
x |> f() |> g(2) |
g(f(x), 2) |
This is why Elixir libraries consistently put the "main" data (the string, the list, the map) as the first parameter: everything composes with |>.
Pipelines with your own functions
Small, named functions make pipelines read like a description of the process:
defmodule Slug do
def from_title(title) do
title
|> String.downcase()
|> String.replace(~r/[^a-z0-9\s-]/, "")
|> String.split()
|> Enum.join("-")
end
end
IO.puts(Slug.from_title("Hello, World! Elixir 1.19 is here"))
IO.puts(Slug.from_title(" Pipes make code readable "))hello-world-elixir-119-is-here
pipes-make-code-readable
Inspecting a pipeline
Because IO.inspect/2 returns its argument, you can put it between any two steps to see the intermediate value. The label: option tells the outputs apart:
[5, 3, 8, 1]
|> IO.inspect(label: "input")
|> Enum.sort()
|> IO.inspect(label: "sorted")
|> Enum.map(&(&1 * 10))
|> IO.inspect(label: "scaled")
|> Enum.sum()
|> IO.inspect(label: "sum")input: [5, 3, 8, 1]
sorted: [1, 3, 5, 8]
scaled: [10, 30, 50, 80]
sum: 170
When the value isn't the first argument
Sometimes the value needs to go somewhere other than the first position. Don't fight the pipe: use then/2, which passes the value to an anonymous function, or bind an intermediate variable:
total =
[19.99, 5.01, 75.0]
|> Enum.sum()
|> then(&Float.round(&1 * 1.21, 2))
IO.inspect(total)
"elixir"
|> String.upcase()
|> then(fn name -> "I love #{name}" end)
|> IO.puts()
# tap/2 runs a side effect and returns the original value
42
|> tap(fn x -> IO.puts("logging #{x}") end)
|> Kernel.+(1)
|> IO.inspect()121.0
I love ELIXIR
logging 42
43
Kernel.+(1) shows that operators are functions too: 42 |> Kernel.+(1) is Kernel.+(42, 1), which is 42 + 1.
Style rules
- Start a pipeline with a plain value, not a function call: prefer
input |> String.trim() |> ...overString.trim(input) |> ...(Credo, the linter, has a rule for this). - Always use parentheses on piped calls:
|> Enum.sum(), not|> Enum.sum. - Avoid single-step pipes like
x |> f(); just callf(x). - Don't pipe into anonymous functions directly (
|> (fn x -> ... end).()); usethen/2.
Common mistake: precedence with arguments
# Wrong: the pipe binds to `String.split/1`, then the result is passed to `IO.inspect`
IO.inspect "a b" |> String.split
# Right
"a b" |> String.split() |> IO.inspect()Without parentheses, the right side of |> can end up being a different call than you intended. Parenthesised calls avoid every ambiguity.
Test yourself
What is "abc" |> String.duplicate(2) equivalent to?
String.duplicate(2, "abc")String.duplicate("abc", 2)"abc" <> String.duplicate(2)- An error
How do you pass a piped value as the second argument of a function?
- Use
|>> - Use
then/2with an anonymous function - It is impossible
- Write
&2
Why is IO.inspect/2 handy inside pipelines?
- It sorts the data
- It prints the value and returns it unchanged
- It converts values to strings
- It stops the pipeline