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].

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).

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

4>​ [2*X || X <- L ].

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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.