-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathcont2.cpp
57 lines (47 loc) · 851 Bytes
/
cont2.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 add(int x,int y)
{
return mreturn<cont>(x+y);
}
auto square(int x)
{
return mreturn<cont>(x*x);
}
auto pyth(int x,int y)
{
return
DO(xx,square(x),
DO(yy,square(y),
add(xx,yy)
));
}
int main()
{
std::cout<<pyth(3,4).run()<<"\n";
}