How to Use Elixir Pipes

mroudnitski

Michael Roudnitski

Posted on January 5, 2021

How to Use Elixir Pipes

A while ago I was introduced to an awesome functional language called Elixir. It's a young ecosystem but has plenty of useful libraries and frameworks, like Phoenix Web Framework which we use on my team here at IBM.

When I was learning Elixir there were completely new concepts I hadn't seen in previous languages. The pipe operator is one of those and it's well worth learning.

The Pipe Operator

Is used to pipe output from one function to another via the 1st argument.

# traditional
myFunction(arg1, arg2, arg3)
# with a pipe
arg1 |> myFunction(arg2, arg3)
Enter fullscreen mode Exit fullscreen mode

All it does is feed the left side into the right side -- riveting!

Example

It's best to teach something like this through examples. Let's say we want to write a function which filters an array and then sorts it.

In JavaScript, we may write something like this:

function filterSort(l) {
  l = l.filter(n => n < 3);
  l = l.sort();
  return l;
}
Enter fullscreen mode Exit fullscreen mode

In Elixir, we can simplify using pipes

def filterSort(l) do
  l
  |> Enum.filter(fn n -> n < 3 end)
  |> Enum.sort()
  # return is not required in Elixir!
end
Enter fullscreen mode Exit fullscreen mode

Here we needed 2 pipes. One to pass the original list into the filter function, and the second to pass our filtered list into sort. We can chain pipes as much as we like. It makes for some really clear and maintainable code when done right.

Debugging with pipes

We can debug effortlessly by adding IO.inspect() (Elixir's equivalent to console.log or print) to our chain of pipes. Continuing from our example, let's inspect the state of our list between each manipulation.

def filterSort(l) do
  l
  |> IO.inspect()
  |> Enum.filter(fn n -> n < 3 end)
  |> IO.inspect()
  |> Enum.sort()
  |> IO.inspect()
  # return is not required in Elixir!
end
Enter fullscreen mode Exit fullscreen mode

This works because IO.inspect() will return whatever value you originally gave it; allowing the pipe to carry on your list to the next function in your chain.

Having a hard time understanding pipes? Feel free to ask questions in the comments!

💖 💪 🙅 🚩
mroudnitski
Michael Roudnitski

Posted on January 5, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related