Used to construct new lists from existing lists.
The notation is
[expressionOfVars |var1 <- listOfVar1Values, var2 <- listOfVar2Values ...]here var1 <- listOfVar1Values is called a generator.
List comprehension can also be used with logical expression called guards to filter the values produced by generators defined to the left of it. If a guard is True then its value is used otherwise it is discarded.
One can also use the generator x <- list as a counter to govern the production of the expressionOfVar by using the wildcard pattern _. Using _ <- list as generator generates expressionOfVar equal to the length of the list.
List comprehensions comes from the comprehensions in mathematics which is the construction of new sets from existing sets. The notation is also similar.
Examples
Relation with mathematics
In mathematics we have that and in Haskell
> [x^2 | x <- [1..5]]
[1,4,9,16,25]List comprehension of multiple variables
> [(x,y) | x <- [1..3], y <- [x..3]]
[(1,1),(1,2),(1,3),(2,2),(2,3),(3,3)]List comprehension with guards
[x | x <- [1..10], even x]
[2,4,6,8,10]References
Programming in Haskell - Graham Hutton