Skip to content

Instantly share code, notes, and snippets.

@ipkn
Last active February 17, 2017 16:22
Show Gist options
  • Save ipkn/f71546b0ae143b2b07bcbe4dce8f1194 to your computer and use it in GitHub Desktop.
Save ipkn/f71546b0ae143b2b07bcbe4dce8f1194 to your computer and use it in GitHub Desktop.
y combinator
// 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