3. List Comprehensions

3 List Comprehensions

3.1 Simple Examples

This section starts with a simple example, showing a generator and a filter:

> [X || X <- [1,2,a,3,4,b,5,6], X > 3].
[a,4,b,5,6]

This is read as follows: The list of X such that X is taken from the list [1,2,a,...] and X is greater than 3.

The notation X <- [1,2,a,...] is a generator and the expression X > 3 is a filter.

An additional filter, integer(X), can be added to restrict the result to integers:

> [X || X <- [1,2,a,3,4,b,5,6], integer(X), X > 3].
[4,5,6]

Generators can be combined. For example, the Cartesian product of two lists can be written as follows:

> [{X, Y} || X <- [1,2,3], Y <- [a,b]].
[{1,a},{1,b},{2,a},{2,b},{3,a},{