fork download
  1. #include <iostream>
  2. #include <functional>
  3. using namespace std;
  4.  
  5. template<typename A, typename B>
  6. using F = function<A(B)>;
  7.  
  8. // Church numeral:
  9. template<typename A>
  10. using CN = F<F<A, A>, F<A, A>>;
  11.  
  12. int churchToInt(CN<int>);
  13.  
  14. template<typename A>
  15. CN<A> zero() {
  16. return [](F<A,A>) -> F<A,A> {
  17. return [](A i) -> A {return i;};
  18. };
  19. };
  20.  
  21. template<typename A>
  22. CN<A> inc(CN<A> n) {
  23. return [=](F<A,A> f) -> F<A,A> {
  24. return [=](A a) -> A {
  25. return n(f)(f(a));
  26. };
  27. };
  28. }
  29.  
  30. template<typename A>
  31. CN<A> operator*(CN<A> a, CN<A> b) {
  32. //printf("I'm %d * %d\n", churchToInt(a), churchToInt(b));
  33. return [=](F<A,A> f) -> F<A,A> {
  34. return b(a(f));
  35. };
  36. }
  37.  
  38. template<typename A>
  39. CN<A> operator+(CN<A> a, CN<A> b) {
  40. //printf("I'm %d + %d\n", churchToInt(a), churchToInt(b));
  41. return [=](F<A,A> f) -> F<A,A> {
  42. return [=](A i) -> A {
  43. auto i1 = a(f)(i);
  44. return b(f)(i1);
  45. };
  46. };
  47. }
  48.  
  49. int churchToInt(CN<int> n) {
  50. auto n2 = n([&](int a)->int {return a+1;});
  51. return n2(0);
  52. }
  53.  
  54. int main() {
  55. auto _0 = zero<int>();
  56. auto _1 = inc<int>(_0);
  57. auto _2 = inc<int>(_1);
  58. auto _3 = inc<int>(_2);
  59. printf("%d\n", churchToInt((_2 + _1) * _3));
  60. return 0;
  61. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
9