Skip to content

Generating Lists from Other Lists: map as a List Comprehension

The expression map f xs can also be written as the list comprehension [f x | x <- xs]. This list comprehension says that we want to construct the list containing all values f x for all values x taken from the list xs.This is exactly the list we get by applying f to every element in xs, that is, the list map f xs.

For example, here is the list of the first 10 positive even numbers:

GHCi
>>> [2*x | x <- [1..10]]
[2,4,6,8,10,12,14,16,18,20]
>>> map (2*) [1..10]
[2,4,6,8,10,12,14,16,18,20]

Or the list of results of testing whether each of the first 5 integers is even or odd:

GHCi
>>> [even x | x <- [1..5]]
[False,True,False,True,False]
>>> map even [1..5]
[False,True,False,True,False]

If you're mathematically inclined, this notation looks refreshingly familiar. We define the set of the first even numbers using remarkably similar syntax:

\[ \{2x \mid x \in \{1, \ldots, 10\}\} \]