fold

Implements the homonym function (also known as accumulate, compress, inject, or foldl) present in various programming languages of functional flavor. The call fold!(fun)(range, seed) first assigns seed to an internal variable result, also called the accumulator. Then, for each element x in range, result = fun(result, x) gets evaluated. Finally, result is returned. The one-argument version fold!(fun)(range) works similarly, but it uses the first element of the range as the seed (the range must be non-empty).

template fold(fun...)
fold
(
R
S...
)
(
R r
,)
if (
fun.length >= 1
)

Members

Functions

fold
auto fold(R r, S seed)

Parameters

fun

the predicate function(s) to apply to the elements

Examples

1 immutable arr = [1, 2, 3, 4, 5];
2 
3 // Sum all elements
4 assert(arr.fold!((a, b) => a + b) == 15);
5 
6 // Sum all elements with explicit seed
7 assert(arr.fold!((a, b) => a + b)(6) == 21);
8 
9 import std.algorithm.comparison : min, max;
10 import std.typecons : tuple;
11 
12 // Compute minimum and maximum at the same time
13 assert(arr.fold!(min, max) == tuple(1, 5));
14 
15 // Compute minimum and maximum at the same time with seeds
16 assert(arr.fold!(min, max)(0, 7) == tuple(0, 7));
17 
18 // Can be used in a UFCS chain
19 assert(arr.map!(a => a + 1).fold!((a, b) => a + b) == 20);
20 
21 // Return the last element of any range
22 assert(arr.fold!((a, b) => b) == 5);

See Also

Fold (higher-order function)

sum is similar to fold!((a, b) => a + b) that offers precise summing of floating point numbers.

This is functionally equivalent to reduce with the argument order reversed, and without the need to use `tuple` for multiple seeds.

Meta

Suggestion Box / Bug Report