![]() |
|
Navigation |
Synopsis Comprehensions provide a concise notation to conditionally generate new values.
Description Comprehensions are defined for the following types:
Each enumerator may introduce new variables that can be used in subsequent generators as well as in the contributing expressions. A generator can use the variables introduced by preceding generators.
Examples A list comprehension:
rascal>[ 3 * X | int X <- [1 .. 10] ];
list[int]: [3,6,9,12,15,18,21,24,27]
A list comprehension with a filter:
rascal>[ 3 * X | int X <- [1 .. 10], X > 5];
list[int]: [18,21,24,27]
A list comprehension with multiple contributing expressions:
rascal>[X, X * X | int X <- [1, 2, 3, 4, 5], X >= 3];
list[int]: [3,9,4,16,5,25]
A set comprehension with a filter:
rascal>{X | int X <- {1, 2, 3, 4, 5}, X >= 3};
set[int]: {3,4,5}
A set comprehension that constructs a relation:
rascal>{<X, Y> | int X <- {1, 2, 3}, int Y <- {2, 3, 4}, X >= Y}; rel[int,int]: { <3,2>, <2,2>, <3,3> } rascal>{<Y, X> | <int X, int Y> <- {<1,10>, <2,20>}}; rel[int,int]: { <10,1>, <20,2> }Introduce a map of fruits and use a map comprehension to filter fruits with an associated value larger than 10:
rascal>fruits = ("pear" : 1, "apple" : 3, "banana" : 0, "berry" : 25, "orange": 35); map[str, int]: ("banana":0,"pear":1,"orange":35,"berry":25,"apple":3) rascal>(fruit : fruits[fruit] | fruit <- fruits, fruits[fruit] > 10); map[str, int]: ("orange":35,"berry":25)See List/Comprehension, Set/Comprehension, or Map/Comprehension for more examples. ![]() |