Created
May 16, 2015 21:58
-
-
Save elbeno/8e369e6138ed21e0db79 to your computer and use it in GitHub Desktop.
Fixed-point (Y) combinator in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <functional> | |
#include <iostream> | |
using namespace std; | |
template <typename F> | |
struct Y | |
{ | |
Y(F f) : m_f(f) {} | |
template <typename T> | |
auto operator()(T&& t) const | |
{ | |
return m_f(*this, std::forward<T>(t)); | |
} | |
F m_f; | |
}; | |
template <typename F> | |
Y<F> fix(F&& f) | |
{ | |
return Y<F>(forward<F>(f)); | |
} | |
int main() | |
{ | |
auto f = fix( | |
[] (auto f, int n) | |
{ | |
if (n == 0) return 1; | |
return n * f(n-1); | |
}); | |
cout << f(4) << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment