August 4, 2015

Erlang/Elixir List Comprehensions

What on Earth is that left arrow operator?

Erlang/Elixir List Comprehensions

I recently took it upon myself to study Handbook of Neuroevolution Through Erlang (a great read by the way, have a look here), but instead of writing neural nets in Erlang, I figured I would convert the examples to Elixir as I learned. Everything went smoothly until this line:

%Chapter 6
FL_NIds = [N#neuron.id || N <- Input_Layer],

What on Earth is that left arrow operator?

Welcome to List Comprehensions

After several unsuccessful attempts at googling "erlang left arrow operator," I finally stumbled across a Google group referencing the same syntax.

So what are they called? List Comprehensions

In functional programming languages, there is no concept of iterations. for loops will not save you. There is no reality but recursion. List comprehensions provide a simple one-liner way to map functions to every element in a list or filter them by certain conditions, all without writing the additional functions that come with recursion.

Want to square every element in a list?

1> [X*X || X <- [1,2,3,4]]
[1,4,9,16]

How about filter every element that's a multiple of 5?

2> [X || X <- [5,6,7,8,9,10], X rem 5 =/= 0].
[6,7,8,9]

What about Elixir?

Heres those same examples rewritten in Elixir:

iex(1)> for n <- [1, 2, 3, 4], do: n * n
[1, 4, 9, 16]
iex(2)> for x <- 5..10, rem(x,5) != 0, do: x
[6, 7, 8, 9]

Ahah! A for loop! Well not really. It still gets compiled into recursive
functions.
Regardless, this syntactic sugar is more palatable to any object-oriented developer.

Final Thoughts

If you haven't ever ventured into functional programming languages, you're
missing a whole new realm of thinking. It's one of the best steps you can take to further your programming knowledge.

Arguing the benefits of functional programming over object-oriented would be best saved for another article, but if you happen to be a Ruby developer, consider taking a look at the Elixir language.