Piping to an anonymous function

Essential Elixir : part 10 of 10 published on May 23, 2016

So you have a value you want to pipe into an anonymous function.

> 3 |> fn(n) -> n + 3 end

Looks good, right? Execute it.

> 3 |> fn(n) -> n + 3 end
** (CompileError) iex:1: expected -> clauses in fn

Doh! Couldn’t even compile. /sad trombone.

Lets take a step back and look at anonymous functions.

First get a reference to the anonymous function.

> f = fn(n) -> n+3 end

Now if we wanted to execute the function f, we use f.().

> f.(3)
6

Nothing scary there. Makes perfect sense. Now lets go backwards and change out our variable f for the anonymous function.

> (fn(n) -> n + 3 end).(3)
6

And now armed with that knowledge on how to execute an anonymous function lets bring back the pipe operator.

> 3 |> (fn(n) -> n + 3 end).()
6

Ta-da! Makes sense now right? I think the best advice in this scenario is to create a named function for the sake of readability, but if you just had to have an anonymous function while piping this is how you do it.