Posted on January 28, 2007 @ 10:47:43 PM by Paul Meagher
One often sees the following set builder notation in mathematics:
{ x^{2}  x in S }
The bar  means "such that" so this expression defines a set that consists of squared x values such that x is in S (where S is itself a set which is left undefined in this example).
The functional programming language Haskell has perhaps the cleanest and most powerful sytax for emulating this set builder notation.
[ x^2  x < [1..5] ]
Hitting return on this list comprehension expression yields:
[1, 4, 9, 16, 25]
The general recipe for list comprehension is [ expression  generator ] where you can have optional additional generators and filters after the bar . With list comprehension we can do some impressive one liners such as:
[ x  x < [1..12], y < [1..12], 12 == x*y ]
Which returns all the factors of 12:
[1, 2, 3, 4, 6, 12]
We can also develop powerful little programs such as this one by O'Donnell, Hall and Page which makes a mailing label for every employee under 30 who is making at least $15000 a year:
db = [("Ann Smith", "29 Byres Road", 30, 48000),
("Alan Jones", "36 High Street", 25, 170000),
...
]
[name ++ "/n" ++ addr ++ "/n"  (name, addr, age, sal) < db, age < 30, sal >= 15000 ]
Cool!
