Skip to content
Elixir

Pipe Operator

Chain function calls with the |> pipe operator.

By EZ4Code Team
pipefunctional

Code

# Without pipe (nested, hard to read)
result = Enum.sum(Enum.filter(Enum.map(1..100, fn x -> x * x end), fn x -> rem(x, 2) == 0 end))

# With pipe (read top-to-bottom)
result =
  1..100
  |> Enum.map(fn x -> x * x end)
  |> Enum.filter(fn x -> rem(x, 2) == 0 end)
  |> Enum.sum()

IO.puts(result)

# Real example: process a string
"hello world"
|> String.upcase()
|> String.split()
|> Enum.join("_")
|> then(&IO.puts/1)  # "HELLO_WORLD"

# With multiple args
[1, 2, 3]
|> Enum.reduce(0, fn x, acc -> acc + x end)  # 6
|> IO.puts()

Explanation

|> takes the left expression's result as the first argument of the right function. This transforms nested calls into a readable top-to-bottom chain. Elixir's standard library is designed for piping — the subject of the operation is always the first parameter. Use then/1 for inline side effects without breaking the chain.

More Elixir Snippets