List comprehension |
List comprehension is a computer programming language construct similar to the set-builder notation ( set comprehensions ), i.e. the mathematical notation
:S={x|x in mathbb{N}, x^2>3}
The earliest reference to the list comprehension notation is in Rod Burstall and John Darlington s description of their programming language, NPL programming language from 1977, but already SETL programming language had a similar construct. In Haskell programming language s list comprehension syntax, the above would be written as S = [ x | x3]
where the list [0..] represents N, and x^2>3 represents the conditional. It is clear that the two notations are almost identical. The example could be read: S is the list of all x where x is an item in the list of natural numbers, and x squared is greater than 3.
Some simple list comprehensions can be rewritten as expressions involving the higher-order functions map and filter.
For example, S above can be alternatively written as S = filter (x -> x^2 > 3) [0..]
However, a list comprehension in Haskell can include any number of the comma-separated qualifiers after the pipe |. Each qualifier is a generator drawing items from a list, a guard (computing) doing filtering, or a local declaration using let. Thus the resulting operation can be complex to express in other means.
The Python_programming_language programming language has a near-equivalent syntax for expressing list comprehensions. The corresponding example would be: L = range(100) # this produces a list of integers from 0 to 99 S = [x for x in L if x**2 > 3]
= Parallel list comprehension =
The Glasgow Haskell Compiler has an extension called parallel list comprehension (also known as zip-comprehension) that permits multiple independent branches of qualifiers. Whereas qualifiers separated by commas are dependent, qualifier branches separated by pipes are evaluated in parallel. First consider the following list comprehension with conventional dependent qualifiers:
[(x,y) | x|
|