reverse_fold

Description

The reverse_fold function adaptor uses a binary function to apply a reverse [fold] (https://en.wikipedia.org/wiki/Fold_%28higher-order_function%29)(ie right fold in functional programming terms) 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 reverse_fold_adaptor<F, State> reverse_fold(F f, State s);

template<class F>
constexpr reverse_fold_adaptor<F> reverse_fold(F f);

Semantics

assert(reverse_fold(f, z)() == z);
assert(reverse_fold(f, z)(x, xs...) == f(reverse_fold(f, z)(xs...), x));
assert(reverse_fold(f)(x) == x);
assert(reverse_fold(f)(x, xs...) == f(reverse_fold(f)(xs...), x));

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::reverse_fold(max_f())(2, 3, 4, 5) == 5);
}