/* Implementation of the Y-combinator. It's questionnable whether this should make into the library or it should just be left as an example file. */ #include #include "prelude.h" using namespace fcpp; using std::cout; using std::endl; /* A functoid to test the fixpoint operator. Implements the Fibonacci function. */ template struct FibGenHelper : public CFunType { X x; FibGenHelper (const X& in_x) : x(in_x) {} int operator () (const int& a) const { if (a == 0 || a == 1) return 1; else return x(a - 1) + x(a - 2); } }; struct FibGen { template struct Sig : public FunType > {}; template FibGenHelper operator () (const X& x) const { return FibGenHelper(x); } } fibgen; /* A dummy routine, just to test the function transformer */ struct Testx : public CFunType { int operator () (const int &) const { return 3; } } testx; template class YHelper { private: F function; public: template struct Sig : public FunType::ResultType,A>::ResultType> {}; YHelper(const F& f) : function(f) {} template typename Sig::ResultType operator () (const A& a) const { // return function(YHelper(function))(a); return function(*this)(a); } }; struct Y { template struct Sig : public FunType > {}; template typename Sig::ResultType operator () (const F& f) const { return YHelper(f); } } y; int main () { cout << "Testing the function transformer." << endl << "Should return 1, 6, 6, actually returned: " << fibgen(testx)(1) << ", " << fibgen(testx)(2) << ", " << fibgen(testx)(3) << "." << endl; cout << "Testing the Y combinator." << endl << "Should return a finonacci sequence, actually returned: "; for (int i = 0; i < 10; i++) cout << y(fibgen)(i) << " "; cout << endl; }