fix

Description

The fix function adaptor implements a fixed-point combinator. This can be used to write recursive functions.

When using constexpr, a function can recurse to a depth that is defined by BOOST_HOF_RECURSIVE_CONSTEXPR_DEPTH(default is 16). There is no limitiation on recursion depth for non-constexpr functions. In addition, due to the eagerness of constexpr to instantiation templates, in some cases, an explicit return type must be specified in order to avoid reaching the recursion limits of the compiler. This can be accomplished using boost::hof::result:

int r = boost::hof::result<int>(factorial)(5);

Synopsis

template<class F>
constexpr fix_adaptor<F> fix(F f);

Semantics

assert(fix(f)(xs...) == f(fix(f), xs...));

Requirements

F must be:

Example

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

int main() {
    auto factorial = boost::hof::fix(
        [](auto recurse, auto x) -> decltype(x) { 
            return x == 0 ? 1 : x * recurse(x-1); 
        }
    );
    int r = boost::hof::result<int>(factorial)(5);
    assert(r == 5*4*3*2*1);
}