foldr

Accumulates all elements of a range using a function.

$(D_PSYMBOL foldr) takes a function, a bidirectional range and the initial value. The function takes this initial value and the first element of the range (in this order), puts them together and returns the result. The return type of the function should be the same as the type of the initial value. This is than repeated for all the remaining elements of the range, whereby the value returned by the passed function is used at the place of the initial value.

$(D_PSYMBOL foldr) accumulates from right to left.

template foldr(F...)
foldr
(
R
T
)
(,
auto ref T init
)
if (
isBidirectionalRange!R
)
if (
F.length == 1
)

Members

Functions

foldr
auto foldr(R range, T init)

Parameters

F

Callable accepting the accumulator and a range element.

Examples

int[3] range = [1, 2, 3];
int[3] output;
const int[3] expected = [3, 2, 1];

alias f = (acc, x) {
    acc.front = x;
    acc.popFront;
    return acc;
};
const actual = foldr!f(range[], output[]);

assert(output[] == expected[]);

Meta