Haskell List Comprehensions
A list comprehension builds a new list from existing ones, using a notation borrowed from mathematics. The set-builder expression { 2x | x ∈ {1..5} } becomes [2 * x | x <- [1 .. 5]] in Haskell.
main :: IO ()
main = do
print [2 * x | x <- [1 .. 5]]
print [x * x | x <- [1 .. 10], even x]
print [c | c <- "Hello World", c /= 'o'][2,4,6,8,10]
[4,16,36,64,100]
"Hell Wrld"
Anatomy
[ expression | generator, generator, ..., condition, ... ]
│ │ │
│ └─ x <- list └─ a Bool expression (a "guard")
└─ what each output element looks like| Part | Example | Meaning |
|---|---|---|
| Output expression | x * x |
Computed for every combination that survives |
| Generator | x <- [1 .. 10] |
Draws each element of a list in turn |
| Guard | even x |
Keeps only elements for which it is True |
| Local binding | let y = x * 3 |
Names an intermediate value |
Filtering with guards
You can use several guards; an element must pass all of them:
main :: IO ()
main = do
let temperatures = [12, 25, 31, 18, 29, 35, 22]
print [t | t <- temperatures, t > 20, t < 30]
print [if t >= 30 then "hot" else "ok" | t <- temperatures]
print (length [t | t <- temperatures, t >= 30])[25,29,22]
["ok","ok","hot","ok","ok","hot","ok"]
2
The second comprehension has no guard: it maps every temperature to a label, using if in the output expression.
Several generators
With two generators, the second one runs completely for each value of the first, like nested loops. Later generators can use earlier variables:
main :: IO ()
main = do
print [(x, y) | x <- [1, 2, 3], y <- "ab"]
-- pairs without duplicates: y starts at x
print [(x, y) | x <- [1 .. 3], y <- [x .. 3]]
-- a small multiplication table
print [x * y | x <- [1 .. 3], y <- [1 .. 3]][(1,'a'),(1,'b'),(2,'a'),(2,'b'),(3,'a'),(3,'b')]
[(1,1),(1,2),(1,3),(2,2),(2,3),(3,3)]
[1,2,3,2,4,6,3,6,9]
A classic: Pythagorean triples
Combining generators and a guard solves search problems in one line. Which right triangles have whole-number sides up to 20?
triples :: Int -> [(Int, Int, Int)]
triples n =
[ (a, b, c)
| c <- [1 .. n]
, b <- [1 .. c]
, a <- [1 .. b]
, a * a + b * b == c * c
]
main :: IO ()
main = mapM_ print (triples 20)(3,4,5)
(6,8,10)
(5,12,13)
(9,12,15)
(8,15,17)
(12,16,20)
Writing a <- [1 .. b] (instead of [1 .. n]) avoids listing each triangle twice as (3,4,5) and (4,3,5). Long comprehensions are easier to read when split over several lines with the commas at the front, as above.
let and patterns in comprehensions
A let inside the comprehension names a value so you don't compute it twice. A generator can also use a pattern to unpack tuples; elements that don't match the pattern are simply skipped:
main :: IO ()
main = do
let prices = [("tea", 3), ("cake", 5), ("juice", 4), ("soup", 7)]
print [name | (name, p) <- prices, p <= 4]
print [(name, total) | (name, p) <- prices, let total = p * 3, total > 10]
let maybes = [Just 1, Nothing, Just 3]
print [x | Just x <- maybes]["tea","juice"]
[("cake",15),("juice",12),("soup",21)]
[1,3]
[x | Just x <- maybes] is a neat idiom for "keep the values that are present". (Just and Nothing are explained in the Maybe lesson.)
Nested comprehensions
The output expression can itself be a comprehension, which is handy for lists of lists such as grids:
main :: IO ()
main = do
let grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print [[x * 10 | x <- row] | row <- grid]
print [x | row <- grid, x <- row, odd x]
print [sum row | row <- grid][[10,20,30],[40,50,60],[70,80,90]]
[1,3,5,7,9]
[6,15,24]
Tip: Comprehensions and
map/filterare interchangeable:[f x | x <- xs, p x]ismap f (filter p xs). Use whichever reads better; comprehensions shine with several generators,map/filterwith function composition.
Test yourself
What is [x | x <- [1 .. 10], mod x 3 == 0]?
[0,3,6,9][3,6,9][1,4,7,10][3,6,9,12]
How many elements does [(a, b) | a <- [1 .. 3], b <- [1 .. 4]] have?
- 7
- 4
- 12
- 3
What does [x | Just x <- [Just 'a', Nothing, Just 'b']] produce?
"ab"- A pattern-match error
[Just 'a', Just 'b']"a"