List comprehensions
A generator and an expression
A list comprehension is set-builder notation that runs. The bar separates what to produce from where the values come from: left of the bar is an expression, right of it is a generator x <- xs, read as "x drawn from xs". The comprehension produces one element of the result per element of the generator, in order.
module Main (main) where
main :: IO ()
main = do
print ([x * x | x <- [1 .. 5]] :: [Int])
print ([x | x <- [1 .. 10], even x] :: [Int])
print ([(x, y) | x <- ([1, 2] :: [Int]), y <- "ab"])
print ([x * 2 | x <- [1 .. 3], let y = x + 1, y > 2] :: [Int])
ghc -Wall -O1 -o comps comps.hs
./comps
[1,4,9,16,25]
[2,4,6,8,10]
[(1,'a'),(1,'b'),(2,'a'),(2,'b')]
[4,6]
The first line is the plain shape: five generators, five results. The second adds a condition after a comma and keeps only the even numbers, so it produces five of the ten candidates. The third has two generators and produces their cartesian product in the order the loops would run: for each x, every y.
Guards in a comprehension
Every comma-separated part after the bar is a qualifier, and the two kinds are a generator and a guard. A guard is an expression of type Bool with no arrow: when it is False, the current element is dropped and the comprehension moves on. Guards are checked in the order they are written, which matters when a later one would divide by zero:
[x | x <- [1 .. 10], even x]
[x | x <- [1 .. 10], even x, x > 5]
[x | x <- [1 .. 10], x /= 0, 100 `div` x < 20]
The last line is the reason order matters: x /= 0 is checked before the division, so the comprehension never divides by zero. Put the division first and the program dies on the first element. This is the same short-circuit idea as &&, written as a list of qualifiers.
let inside a comprehension
A qualifier can also be a let, which names a value for the rest of the comprehension. The scope runs from the let to the end of the qualifier list and into the expression, so later guards and the result can both use it:
[y | x <- [1 .. 3], let y = x + 1, y > 2] -- [3,4]
[x * 2 | x <- [1 .. 3], let y = x + 1, y > 2] -- [4,6]
The second line is the fourth line of the program, and it prints [4,6]: the values of x are 1, 2 and 3, the values of y are 2, 3 and 4, the guard keeps 2 and 3, and the result is twice the x that produced them. The first line shows the same binding with y itself as the result, so it prints [3,4]. A let in a comprehension is not a generator: it produces nothing, it only names. If the value is needed once, writing it in the expression is shorter; it earns its place when two guards or the result would otherwise repeat the same arithmetic.
Nested generators
Two generators nest in the order they are written: the second runs its whole range for every value of the first. That is exactly two nested loops, and it is why the third line of the program prints four pairs and not three: the lengths multiply, not add.
[(x, y) | x <- [1, 2], y <- "ab"]
[(x, y) | x <- "ab", y <- [1, 2]] -- the other order
[(x, y) | x <- [1 .. 3], y <- [x .. 3]] -- the inner range sees x
The third line is the idiom worth remembering: a generator may use a variable bound by an earlier generator, so the inner range depends on the outer one. That is how a triangular table is written without arithmetic in the expression. Swapping two independent generators transposes the result and changes nothing else.
Pythagorean triples
A search with three nested generators and one guard is the classic comprehension, and it is short enough to read as the definition: integers a, b, c up to a limit with a <= b <= c and a² + b² = c².
module Main (main) where
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 = print (triples 20)
ghc -Wall -O1 -o pyth pyth.hs
./pyth
[(3,4,5),(6,8,10),(5,12,13),(9,12,15),(8,15,17),(12,16,20)]
Six triples below 20, and the order is the one the loops produce: by c first, then b, then a. Note that the guard does not sort anything: the bounds on the generators do the ordering, which is why the inner ranges are written in terms of the outer variables rather than filtered afterwards. The same search written with three nested case blocks would be a page of code; the comprehension is a line and a half.
The cost is honest too: the three ranges produce about n³/6 candidates, so 20 is instant and 2000 is not. The lesson on folds shows how the same list can be consumed without building it, and the one on laziness explains why take 1 (triples 100000) can still answer.
Exercises
- Print the squares of the odd numbers from 1 to 15 in one comprehension.
- Build [(x, y) | x <- [1 .. 3], y <- [1 .. x]] and count the pairs by eye, then with length.
- Use a let qualifier to print the length of each word of ["one", "three", "seven"].
- Write a comprehension whose guard divides by the element, with the zero check first, and one with the order swapped; run both.
- Change triples so that it also requires a + b + c <= 30 and print the result for 20.
- Rewrite [x * x | x <- [1 .. 5]] as map (\x -> x * x) [1 .. 5] and compare.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
[x * 2 | x <- [1 .. 3]]evaluate to?Answer
[2,4,6]
The generator draws 1, 2 and 3 and the expression doubles each, giving three elements.
-
What does
[x | x <- [1 .. 10], even x]produce?Answer
[2,4,6,8,10]
The guard keeps the candidates for which even x is True, which are the five even numbers up to 10.
-
How many elements does
[(x, y) | x <- [1, 2], y <- "ab"]have?Answer
4
The generators multiply: two values of x times two characters, so four pairs.
-
What is the guard in a comprehension?
Answer
A Bool expression that drops the current element when it is False
A qualifier without an arrow is a condition: False drops the element, True keeps it.
-
What does this program print?
module Main (main) where main :: IO () main = print ([x * 2 | x <- [1 .. 3], let y = x + 1, y > 2] :: [Int])Answer
[4,6]
y is 2, 3, 4; the guard keeps the x values 2 and 3, and the expression doubles them to 4 and 6.
-
Why does the comprehension
[100divx | x <- [1 .. 10], x /= 0, ...]checkx /= 0before the division?Answer
Qualifiers run left to right, so an early False stops the element
A guard that fails drops the element before later qualifiers run, so the order is the short circuit.
-
What does
[(x, y) | x <- [1 .. 2], y <- [x .. 2]]produce?Answer
[(1,1),(1,2),(2,2)]
The inner range starts at the current x: for x = 1 it gives 1 and 2, for x = 2 it gives only 2.
-
In
triples, why are the generators ordered c, then b, then a?Answer
Each inner range is bounded by the outer variable, which keeps a <= b <= c without a filter
b runs up to c and a up to b, so every candidate already satisfies a <= b <= c and the guard only tests the squares.
-
What does this program print?
module Main (main) where main :: IO () main = print [(x, y) | x <- "ab", y <- [1, 2]]Answer
[('a',1),('a',2),('b',1),('b',2)]
The outer generator is the string and the inner one is the list of numbers, so the pairs are characters with numbers in that order.
-
Which function can replace
[f x | x <- xs]without changing the result?Answer
map f xsA comprehension with one generator and no guards is map: one result element per input element.
The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev