The beauty of Elixir pipe operator

By Michael Anckaert - published on - posted in Programming

I've been programming more in Elixir lately and just wanted to write something about the beauty of the pipe operator.

In a functional language we're used to working with pure functions. This almost always leads to situations where we pass a value from one function to another, creating a sort of mini pipeline to manipulate our data. In textual schematic form: data -> function1 -> function2 -> function3 -> result.

In most languages, this leads to either nested function calls:

defmodule MyPipeline do
  def run do
    function3(function2(function1()))
  end
end

or use of intermediate variables:

defmodule MyPipeline do
  def run do
    var1 = function1()
    var2 = function2(var1)
    result = function3(var2)
  end
end

But in Elixir, we have access to the pipe operator |>. As the name says, this operator acts like a pipe between function. With the pipe operator, our previous example simply becomes:

defmodule MyPipeline do
  def run do
    function1() |> function2() |> function3()
  end
end

It also works when a function takes more than one argument:

defmodule MyPipeline do
  def run do
    function1() |> function2(17) |> function3()
  end
end

As the result of the previous function get passed as the first argument in the next function, the above example will result in a call to function2 which equals function2(function1(), 17).

Using the pipe operator leads to very readable code, which often maps almost directly to pseudo code, schematics or designs. In the example below the code speaks for itself:

 def get_statuses_for_profile(id) do
    get_url(id)
    |> get_data
    |> decode_data
    |> filter_threads
    |> exclude_reblogs
    |> print_statuses
  end