Skip to main content

Mastering the Pipe Operator (|>): Streamline Your Elixir Code

Elixir’s

pipe operator (|>) lets you chain function calls in a clear, left‑to‑right flow—making data transformations concise and readable.

# We start with a range of numbers 1 through 10
1..10
|> Enum.map(&(&1 * 3))        # Triple each number
|> Enum.filter(&rem(&1, 2) == 0)  # Keep only the even results
|> Enum.take(3)               # Take the first three elements

Output in IEx:

[6, 12, 18]

Why Use |>?

  • Readability:
    You read it like a pipeline—“take 1..10, triple them, filter evens, then take three.”

  • No Nested Calls:
    Without piping, you’d write:

    Enum.take(
      Enum.filter(
        Enum.map(1..10, &(&1 * 3)),
        &rem(&1, 2) == 0
      ),
      3
    )
    

    which gets hard to follow as you nest more operations.

  • Flexibility:
    You can insert or remove steps without re‑parenthesizing everything.

Takeaways

  • Use |> to pass the result of the left expression as the first argument to the function on the right.
  • Ideal for chaining transformations on collections (using Enum or Stream).
  • Makes your code read top‑to‑bottom, improving maintainability and reducing cognitive load.

By embracing the pipe operator, your Elixir code becomes both more elegant and easier to reason about.

Happy piping!

Comments