Skip to content

Instantly share code, notes, and snippets.

@elbeno
Created May 16, 2015 21:58
Show Gist options
  • Save elbeno/8e369e6138ed21e0db79 to your computer and use it in GitHub Desktop.
Save elbeno/8e369e6138ed21e0db79 to your computer and use it in GitHub Desktop.
Fixed-point (Y) combinator in C++
#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