Jump to content

Y combinator: Difference between revisions

m (Y combinator implementation in Q : https://code.kx.com/q/)
Line 1,902:
return YFunctor<A,B>(f);
}</lang>
{{works with|C++17}}
<lang cpp>
#include <stdio.h>
template<typename FF,typename F>
struct G;
template<typename FF,typename RT,typename ...Args>
struct G<FF,RT(Args...)> {
FF const f;
struct Z {
G const g;
constexpr Z(FF const f) : g{f} {}
constexpr RT operator()(Args ...args)const{
return g.f(g())(args...);
}
};
constexpr Z operator()()const{
return Z{f};
}
};
template<typename F>
struct _Y;
template<typename RT,typename ...Args>
struct _Y<RT(Args...)> {
template<typename F>
constexpr auto operator()(F f)const{
return [f](auto g){
return f(g);
}(G<F,RT(Args...)>{f}());
}
};
template<typename F>
constexpr auto Y=_Y<F>{};
int main(){
constexpr auto almost_fac=[](auto f){
return [f](auto n,auto acc){
return (n == 0) ? acc : f(n-1,n*acc);
};
};
constexpr auto almost_fib = [] (auto f) {
return [f] (auto n) {
return n < 2? n: f (n - 1) + f (n - 2);
};
};
constexpr auto fac =[](long n){
return Y<long(long,long)>(almost_fac)(n,1);
};
constexpr auto fib =Y<long(long)>(almost_fib);
printf("%ld\n",fib(10));
printf("%ld\n",fac(10));
}</lang>
{{out}}
<pre>
55
3628800
</pre>
 
=={{header|Ceylon}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.