I'm learning C++. As an exercise to myself, I'm trying to define the Fibonacci function from a non-recursive version using a Y combinator.
In F# (or C#) I'd do it like this:
let rec Y f n = f (Y f) n
let protoFib f x = if n > 1 then f(n-1) + f(n-2) else n
let fib = Y protoFib
In C++ I am stuck how to define Y
So that the following lines work
int protoFib(int f(int), int n) {
return (n > 1) ? f(n-1) + f(n-2) : n;
}
int fib(int n) { return Y(protoFib, n); }
I tried the following function declaration (specific to int functions because I've not yet studied templates):
#include <functional>
int Y(std::function<int(std::function<int(int)>, int)>, int);
but I am stuck on writing the function definition.
Any suggestions?
from the rosseta stone https://rosettacode.org/wiki/Y_combinator#C.2B.2B for the Y combinator:
I recommend you check the whole code for that example, as it contains other ways of implementing it (e.g. using lambdas)