map(), it is helpful to explain
reduce() from the
std.algorithm module first.
reduce() is the equivalent of
std.algorithm.fold, which you have seen before. The main difference between the two is that their function parameters are reversed. (Therefore, we recommend that you favor
fold() for non-parallel code as it can take advantage of UFCS in chained range expressions.)
reduce() is another high-level algorithm commonly found in many functional languages. Just like
map(), it takes one or more functions as template parameters. As its function parameters, it takes a value to be used as the initial value of the result, and a range.
reduce() calls the functions with the current value of the result and each element of the range. When no initial value is specified, the first element of the range is used instead.
Assuming that it defines a variable named result in its implementation, the way that
reduce() works can be described by the following steps:
- Assigns the initial value to result
- Executes the expression result = func(result, element) for every element
- Returns the final value of result
For example, the sum of the squares of the elements of an array can be calculated as in the following program: