Skip to content
Elixir

Operador Pipe

Encadear chamadas de função com o operador pipe |>.

#pipe#functional

Code

elixir
# 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()