the predicate function(s) to apply to the elements
immutable arr = [1, 2, 3, 4, 5]; // Sum all elements assert(arr.fold!((a, b) => a + b) == 15); // Sum all elements with explicit seed assert(arr.fold!((a, b) => a + b)(6) == 21); import std.algorithm.comparison : min, max; import std.typecons : tuple; // Compute minimum and maximum at the same time assert(arr.fold!(min, max) == tuple(1, 5)); // Compute minimum and maximum at the same time with seeds assert(arr.fold!(min, max)(0, 7) == tuple(0, 7)); // Can be used in a UFCS chain assert(arr.map!(a => a + 1).fold!((a, b) => a + b) == 20); // Return the last element of any range assert(arr.fold!((a, b) => b) == 5);
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).