Reducer
rascal-0.40.17
Synopsis
Reduce generated values to a single value.
Syntax
( InitExp | RedExp | Gen₁, Gen₂, ... )
Description
Reducers are comprehesions (see list comprehension, set comprehension) that construct any type of value by an iterating rather than just a list or a set.
Every reducer (as above) is equivalent to the following code:
it = _InitExp_; ❶
for(_Gen₁_, _Gen₂_, ... ) ❷
it = _RedExp_; ❸
it; ❹
and is executed as follows:
- A fresh variable, always named
it
, is initialized with InitExp. We call the variableit
since we useit
to initialize the reducer, to make changes toit
, and to returnit
as result. - A for loop iterates over all values produced by the generators
Gen₁
,Gen₂
, ... . - In the body of the loop, variable
it
is updated to reflect a new reduced value. Note thatit
itself and variables introduced in Gen₁, Gen₂, ... may occur in RedExp. - The final value of
it
is the result of the reducer.
Examples
rascal>L = [1, 3, 5, 7];
list[int]: [1,3,5,7]
rascal>(0 | it + e | int e <- L);
int: 16
rascal>(1 | it * e | int e <- L);
int: 105
Benefits
- A reducer resembles the fold function found in most functional languages.