Y combinator: Difference between revisions
Content deleted Content added
Line 1,902: | Line 1,902: | ||
return YFunctor<A,B>(f); |
return YFunctor<A,B>(f); |
||
}</lang> |
}</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 f; |
|||
struct Z { |
|||
G g; |
|||
constexpr Z(FF 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 = Y<long(long,long)>(almost_fac); |
|||
constexpr auto fib = Y<long(long)>(almost_fib); |
|||
constexpr auto fac_10 = fac(10,1); |
|||
constexpr auto fib_10 = fib(10); |
|||
printf("%ld\n",fib_10); |
|||
printf("%ld\n",fac_10); |
|||
}</lang> |
|||
{{out}} |
|||
<pre> |
|||
55 |
|||
3628800 |
|||
</pre> |
|||
=={{header|Ceylon}}== |
=={{header|Ceylon}}== |