Erlang Notes – List comprehensions

Here is the sixth of some notes about erlang.
Obviously this is a very cursory glance at things. It’s really just notes to help me remember things. If you’re looking for something in more detail you can take a look at the erlang reference manual.

List comprehensions

I first encountered List Comprehensions in Python, and they were one of the things I loved, and missed as I started working in Ruby more. In principle, they are a simple way to define a mapping from one list to another. Here’s the notation in Erlang:

[2*X || X <- L].

This concise piece of code says something like: take each of the elements from the list L, and map them as element X into a new list defined by the function 2 times X.

Of course, the function you apply to the elements of the list could be a good deal more complex, and probably would be in real life.

There are some quite interesting isolated examples of list comprehension in Joe Armstrong’s book, including a terse quicksort implementation, but I don’t think there’s much more to say about them here, out of the context of a real application

Leave a Comment