8.23 List Comprehensions
List comprehensions is a feature of many modern functional programming languages. Subject to certain rules, they provide a succinct notation for generating elements in a list.
List comprehensions are analogous to set comprehensions in Zermelo-Frankel set theory and are called ZF expressions in Miranda. They are analogous to the setof and findall predicates in Prolog.
List comprehensions are written with the following syntax:
- [Expr || Qualifier1,...,QualifierN]
Here, Expr is an arbitrary expression, and each Qualifier is either a generator or a filter.
- A generator is written as: Pattern <- ListExpr. ListExpr must be an expression, which evaluates to a list of terms.
- A bit string generator is written as: BitstringPattern <= BitStringExpr. BitStringExpr must be an expression, which evaluates to a bitstring.
- A filter is an expression, which evaluates to true or false.The variables in the generator patterns, shadow variables in the function clause, surrounding the list comprehensions.
A list comprehension returns a list, where the elements are the result of evaluating Expr for each combination of generator list elements and bit string generator elements, for which all filters are true.
Example:
- 1> [X*2 || X <- [1,2,3]].
- [2,4,6]
When there are no generators or bit string generators, a list comprehension returns either a list with one element (the result of evaluating Expr) if all filters are true or an empty list otherwise.
Example:
- 1> [2 || is_integer(2)].
- [2]
- 2> [x || is_integer(x)].
- []
More examples are provided in Programming Examples.