Having fun with Pipes

Recently I have been playing around with Elixir. There are many great things about this language but one of my favourites is the pipe operator (|>).

It basically allows you to turn something like this:

fn3(fn2(fn1(x)), y)  

into this:

fn1(x) |> fn2(y) |> fn3  

It looks so much better! What it's doing is basically passing the result of fn1(x) as the first argument of fn2 and the result of fn2(fn1(x)) as the first argument of fn3.

Now, the best thing about pipes is when you're applying a chain of transformations in some sort of collection. On both the Enum and Stream modules, all functions receive the collection to process as first argument.

Lets say we have a list of numbers and we want to filter the even ones, then double them and finally, sum them. You could write like this:

numbers = [1,2,3,4,5,6,7,8,9,10]

Stream.filter(numbers, &(rem(&1, 2) == 0))  
  |> Stream.map(&(&1 * 2)) 
  |> Enum.reduce(&(&1 + &2))

I think that looks pretty cool!