The pipe operator in Elixir

Published October 03, 2018 by Toran Billups

In part 10 of my Elixir journey I'll be sharing a brief introduction to the pipe operator.

Pipe Operator

If my procedural upbringing has taught me anything it's that you can chain one function call after another to accomplish just about everything.

    defmodule Math do
      defp add(a, b), do: a + b
      defp multiply(a, b), do: a * b
      defp divide(a, b), do: a / b
      def magic() do
        two = add(1, 1)
        six = multiply(two, 3)
        result = divide(six, 2)
        IO.puts result
      end
    end
  

In this example I'm using a handful of private functions to do `magic` and print out the result. This style of programming makes it clear what each function recieves as input and returns as output. One less verbose alternative is function chaining, but in most languages this requires the reader to work inside out which feels unintuitive.

    result = divide(multiply(add(1, 1), 3), 2)
  

Elixir offers the best of both worlds with the fabulous pipe operator. You work left to right, instead of inside out, so the flow of information is more natural for the reader. Also, the output of each function in the chain becomes the first parameter of the function that follows.

    defmodule Math do
      defp add(a, b), do: a + b
      defp multiply(a, b), do: a * b
      defp divide(a, b), do: a / b
      def magic() do
        result = add(1, 1)
          |> multiply(3)
          |> divide(2)
        IO.puts result
      end
    end
  

The pipe operator works well multi-line as shown above but it also supports single line chaining if you prefer.

    defmodule Math do
      defp add(a, b), do: a + b
      defp multiply(a, b), do: a * b
      defp divide(a, b), do: a / b
      def magic() do
        result = add(1, 1) |> multiply(3) |> divide(2)
        IO.puts result
      end
    end
  

This syntax in particular has encouraged me to embrace a more functional way of thinking in the language.


Buy Me a Coffee

Twitter / Github / Email