-
-
Save ipkn/f71546b0ae143b2b07bcbe4dce8f1194 to your computer and use it in GitHub Desktop.
y combinator
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
// main() from https://github.com/simnalamburt/snippets/blob/master/cpp/y-combinator.cpp which is licensed under the Apache License 2.0. | |
// Apache-2.0/MIT. | |
// -------- | |
#include <stdint.h> | |
#include <iostream> | |
template <typename Func> | |
auto y(Func f) { | |
auto g = [f](auto r){ | |
return [f,r](auto&&...z){ | |
return f(r(r),z...); | |
}; | |
}; | |
return g(g); | |
} | |
int main() { | |
auto fact = y([](auto fact, uint64_t n)->uint64_t { | |
return n == 0 ? 1 : n * fact(n-1); | |
}); | |
auto gcd = y([](auto gcd, uint64_t a, uint64_t b)->uint64_t { | |
return b == 0 ? a : gcd(b, a%b) ; | |
}); | |
std::cout << fact(15) << std::endl; | |
std::cout << gcd(135, 225) << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment