Created
May 20, 2016 00:41
-
-
Save na-o-ys/56434282baa5705efe7e3bd05e3f04d1 to your computer and use it in GitHub Desktop.
Anonymous Recursion 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
// $ 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