List Comprehensions

List comprehensions are expressions that create lists without having to use funs, maps, or filters. This makes our programs even shorter and easier to understand.

We’ll start with an example. Suppose we have a list L.

 
1>​ L = [1,2,3,4,5].
 
[1,2,3,4,5]

And say we want to double every element in the list. We’ve done this before, but I’ll remind you.

 
2>​ lists:map(fun(X) -> 2*X end, L).
 
[2,4,6,8,10]

But there’s a much easier way that uses a list comprehension.

 
4>​ [2*X || X <- L ].
 
[2,4,6,8,10]

The notation [ F(X) || X <- L] means “the list of F(X) where X is taken from the list L.” Thus, [2*X || X <- L ] means “the list of 2*X where X is taken from the list L.”

To see how to use a list comprehension, we can enter ...

Get Programming Erlang, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.