Skip to content

Instantly share code, notes, and snippets.

@na-o-ys
Created May 20, 2016 00:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save na-o-ys/56434282baa5705efe7e3bd05e3f04d1 to your computer and use it in GitHub Desktop.
Save na-o-ys/56434282baa5705efe7e3bd05e3f04d1 to your computer and use it in GitHub Desktop.
Anonymous Recursion in C++
// $ g++-4.9 -std=c++1y anonymous_rec.cpp
#include <iostream>
template<typename Func>
struct fixed {
Func f;
template<typename... Args>
auto operator()(Args... args) {
return f(fix(f), args...);
}
};
template<typename Func>
fixed<Func> fix(Func f) {
return { f };
}
int main()
{
// fib(4) => 5
std::cout << (fix([](auto self, int n) -> int {
return n <= 1 ? 1 : self(n-1) + self(n-2);
}))(4) << std::endl;
// gcd(15, 9) => 3
std::cout << (fix([](auto self, int a, int b) -> int {
return b == 0 ? a : self(b, a % b);
}))(15, 9) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment