fold

Description

The fold function adaptor uses a binary function to apply a fold operation to the arguments passed to the function. Additionally, an optional initial state can be provided, otherwise the first argument is used as the initial state.

The arguments to the binary function, take first the state and then the argument.

Synopsis

template<class F, class State>
constexpr fold_adaptor<F, State> fold(F f, State s);

template<class F>
constexpr fold_adaptor<F> fold(F f);

Semantics

assert(fold(f, z)() == z);
assert(fold(f, z)(x, xs...) == fold(f, f(z, x))(xs...));
assert(fold(f)(x) == x);
assert(fold(f)(x, y, xs...) == fold(f)(f(x, y), xs...));

Requirements

State must be:

  • CopyConstructible

F must be:

Example

#include <boost/hof.hpp>
#include <cassert>

struct max_f
{
    template<class T, class U>
    constexpr T operator()(T x, U y) const
    {
        return x > y ? x : y;
    }
};
int main() {
    assert(boost::hof::fold(max_f())(2, 3, 4, 5) == 5);
}

References