-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathcont3.cpp
57 lines (48 loc) · 950 Bytes
/
cont3.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <functional>
template<typename T>
class cont
{
public:
cont(const T& x):run_([=](){return x;}){}
template<typename F>
cont(const cont& c,F f):run_([=](){return f(c.run()).run();}){}
T run()const{return run_();}
private:
std::function<T()> run_;
};
template<template<typename> class M,typename T>
M<T> mreturn(const T& x)
{
return x;
}
template<typename T,typename F>
auto operator>>=(const cont<T>& c, F f)
{
return cont<T>{c,f};
}
#define DO(var,monad,body) \
((monad)>>=[=](const auto& var){ \
return body; \
})
auto fac(int n)
{
std::cout<<"constructing fac("<<n<<")\n";
if(n==0){
return mreturn<cont>(1);
}
else{
return
DO(m,fac(n-1),(
std::cout<<"computing "<<m<<"*"<<n<<"\n",
mreturn<cont>(m*n)
));
}
}
int main()
{
auto f=fac(5);
std::cout<<"running f\n";
auto r=f.run();
std::cout<<"fac(5)="<<r<<"\n";
}