View source code
Display the source code in std/algorithm/iteration.d from which thispage was generated on github.
Report a bug
If you spot a problem with this page, click here to create aBugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.Requires a signed-in GitHub account. This works well for small changes.If you'd like to make larger changes you may want to consider usinglocal clone.

Template std.algorithm.iteration.fold

Implements the homonym function (also known as accumulate, compress, inject, or foldl) present in various programming languages of functional flavor, iteratively calling one or more predicates.

template fold(fun...);

Each predicate in fun must take two arguments:

* An accumulator value * An element of the range r

Each function must return a value which implicitly converts to the type of the accumulator.

For a single function, the call fold!(fun)(range, seed) will:

* Use seed to initialize an internal accumulator. * For each element e in range, evaluate accumulator = fun(result, e). * Return accumulator.

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) and iterates over the remaining elements.

Multiple results are produced when using multiple functions.

If range has only one element, the functions are never invoked and result and the seed is returned unchanged.

Contained Functions

NameDescription
fold

Parameters

NameDescription
fun one or more functions of the form Acc function(Acc, ElemT)

See Also

* Fold (higher-order function)

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

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

Example

immutable arr = [1, 2, 3, 4, 5];

// Sum all elements
writeln(arr.fold!((a, e) => a + e)); // 15

// Sum all elements with explicit seed
writeln(arr.fold!((a, e) => a + e)(6)); // 21

import std.algorithm.comparison : min, max;
import std.typecons : tuple;

// Compute minimum and maximum at the same time
writeln(arr.fold!(min, max)); // tuple(1, 5)

// Compute minimum and maximum at the same time with seeds
writeln(arr.fold!(min, max)(0, 7)); // tuple(0, 7)

// Can be used in a UFCS chain
writeln(arr.map!(a => a + 1).fold!((a, e) => a + e)); // 20

// Return the last element of any range
writeln(arr.fold!((a, e) => e)); // 5

Authors

Andrei Alexandrescu

License

Boost License 1.0.