First I'll write a bad, if functional, Y-combinator.
using fib_f = std::function<int(int)>;
using protofib_f = std::function< int( fib_f, int ) >;
int protofib( std::function<int(int)> f, int n) {
if (n>1) return f(n-1)+f(n-1);
return n;
}
auto Y( protofib_f f )->fib_f {
return [=](int n) { return f( Y(f), n ); };
}
ugly, but it works.
We can write a better Y combinator.
template<class R>
auto Y = [&](auto&& f){
return [=](auto&&...args)->R {
return f( Y<R>(f), decltype(args)(args)... );
};
};
which, to be simple, does need to have its return type specified.
auto fib = Y<int>(protofib);
it also defers type erasure, which gives performance.
We can strip type erasure form protofib:
auto protofib = [](auto&& f, int n)->int {
if (n>1) return f(n-1)+f(n-1);
return n;
};
by turning it into a lambda.
An improved Y combinator requires a bit more boilerplate, because lambdas cannot access this:
template<class F>
struct y_combinate_t {
F f;
template<class...Args>
decltype(auto) operator()(Args&&...args)const {
return f(*this, std::forward<Args>(args)...);
}
};
template<class F>
y_combinate_t<std::decay_t<F>> y_combinate( F&& f ) {
return {std::forward<F>(f)};
};
again, zero type erasure overhead, and this one doesn't require the return type being passed explicitly. (stolen from myself over here).
In c++17 the y_combinate
helper can be eliminated:
template<class F>
struct y_combinate {
F f;
template<class...Args>
decltype(auto) operator()(Args&&...args)const {
return f(*this, std::forward<Args>(args)...);
}
};
template<class F>
y_combinate(F&& f)->y_combinate<std::decay_t<F>>;
with a deduction guide.
y_combinate{ protofib }
is then a full fibbonacci function.
Live example.
Going a step further, you could add memoization to your y combinator.