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
`1`

, `2`

, and `3`

in
turn. Going into the output for each of these is `X+1`

, the expression before the symbol `||`

, `1`

leading to `2`

, and so on. This gives
the result `[2,3,4]`

.

1>[2,3,4]`[X+1 || X <- [1,2,3]].`

In the next code snippet, there is a filter, `X rem 2 == 0`

, which selects only those
`X`

s that pass this test. Here, that
`X`

is even:

2>[2]`[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.

3>[3]`[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:

```
[ Expression || Generators, Guards,
Generators, ... ]
``` |

- Generators
A generator has the form

`Pattern <- List`

, where`Pattern`

is a pattern that is matched with elements from the`List`

expression. ...

Start Free Trial

No credit card required