🎓 A1Learner
🔍
0 of 54 lessons completed

Haskell List Comprehensions

A list comprehension is an expression that builds a new list by taking values from a list and changing or keeping each one. It has a result expression, a generator, and optional guards.

The result expression changes each value

Each value taken from the list is doubled before it enters the new list.

main :: IO ()
main = print [x * 2 | x <- [1, 2, 3, 4]]

A guard keeps only passing values

The guard keeps only the words longer than two characters.

main :: IO ()
main = print [word | word <- ["hi", "hello", "hey"], length word > 2]

Two generators give every pairing

Each value from the first list is paired with each value from the second list.

main :: IO ()
main = print [(x, y) | x <- [1, 2], y <- [10, 20]]

Example

main :: IO ()
main = print [n * n | n <- [1..5], n /= 3]

Key points

  • Shape: a comprehension sits inside square brackets and starts with its result expression.
  • Generator: the part x <- [1, 2, 3] takes each value in turn and names it x.
  • Result expression: the expression before the bar can change each value, as in x * 2.
  • Guard: a condition after the generator keeps only the values that pass it.
  • Several generators: two generators give every pairing of the values from the two lists.
  • New list: a comprehension builds a new list and leaves the source list unchanged.

In this example, the generator takes each number from 1 to 5 in turn. The guard n /= 3 removes 3, and the result expression squares each number that remains, giving [1,4,16,25].

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

What is the value of [x + 1 | x <- [10, 20, 30]]?