The OpenD Programming Language

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)(slice, seed) first assigns seed to an internal variable result, also called the accumulator. Then, for each element x in slice, result = fun(result, x) gets evaluated. Finally, result is returned.

template fold(alias fun)
fold
(
Slice
S
)
(
scope Slice slice
,)

Members

Functions

fold
auto fold(Slice slice, S seed)

Parameters

fun

the predicate function to apply to the elements

Examples

import mir.ndslice.slice: sliced;
import mir.ndslice.topology: map;

auto arr = [1, 2, 3, 4, 5].sliced;

// Sum all elements
assert(arr.fold!((a, b) => a + b)(0) == 15);
assert(arr.fold!((a, b) => a + b)(6) == 21);

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

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

Works for matrices

import mir.ndslice.fuse: fuse;

auto arr = [
    [1, 2, 3], 
    [4, 5, 6]
].fuse;

assert(arr.fold!((a, b) => a + b)(0) == 21);

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.

Meta