tuple_fold(3) | tuple_fold(3) |
tuple_fold - tuple reduction
#include <cfl/tuple/tuple_fold.hpp>
template <typename F, typename I, typename... ARGS>
auto tuple_fold (F && f, I && i, ARGS &&... args);
auto f = [] (int a, int b) { return a + b; };
tuple_fold (f, 1, tuple (2, 3)) == 6;
Roughly, tuple_fold
reduces a collection of elements to a single value using a
binary function. This operation is also known as reduce, accumulate and
compress.
tuple_fold
reaches a final result r(n)
by successive application of a
function f
to the result of the previous application r(n-1)
and the elements
of tuples args
, starting with the initial value i
.
f
must have an arity of at least two. For higher arities, tuple_fold
maps
trailing arguments. The first argument is always used for the initial value or
the previous result.
// ternary multiply-and-accumulate
auto f = [] (int i, int a, int b) { return i + a * b; };
auto u = tuple (1, 2);
auto v = tuple (3, 4);
// map trailing argument v
tuple_fold (f, 0, u, v) == 11;
f
may be shape-polymorphic, i.e. accepting arguments of arbitrary shape.
There are other variants of fold: reversed element traversal (tuple_foldl
) and
recursive folding of nested tuples (tuple_fold_all
).
auto f = [] (int a, int b) { return -a + b; };
tuple_fold (f, 1, tuple (2, 3)) == 2;
tuple_foldl (f, 1, tuple (2, 3)) == 0;
tuple_fold_all (f, 1, tuple (2, tuple (3))) == 2;
tuple_foldl_all (f, 1, tuple (2, tuple (3))) == 0;
tuple_fold
and its variants are container functions.
tuple(3), tuple_scan(3)