Typical of operations on lists are mapping—applying a function to every element of a list—and filtering—selecting those elements of a list that have a particular property. Often these are used together, and the list comprehension notation gives you a powerful and compact way to write down lists constructed in this way. We’ll begin with some simple examples, and then look in more detail at a simple database case study.
The list comprehension in the following code has the generator
X <- [1,2,3], which means
X runs through the values
turn. Going into the output for each of these is
X+1, the expression before the symbol
2, and so on. This gives
[X+1 || X <- [1,2,3]].[2,3,4]
In the next code snippet, there is a filter,
X rem 2 == 0, which selects only those
Xs that pass this test. Here, that
X is even:
[X || X <- [1,2,3], X rem 2 == 0].
The following code combines the two: the even elements of
[1,2,3] are selected, and
1 is added to each of them.
[X+1 || X <- [1,2,3], X rem 2 == 0].
These are the basics of list comprehension. Next, we’ll discuss what a list comprehension is like in general, before looking at a larger example.
In general, a list comprehension has three component parts:
A generator has the form
is a pattern that is matched with elements from the
List expression. ...