-
Notifications
You must be signed in to change notification settings - Fork 10
/
cont3++.cpp
54 lines (45 loc) · 901 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
#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};
}
struct fac_state{int n,res;};
auto fac_impl(const fac_state& s)
{
std::cout<<"constructing fac_impl("<<s.n<<")\n";
if(s.n==0){
return mreturn<cont>(s);
}
else{
return fac_impl(fac_state{s.n-1,s.res*s.n});
}
}
auto fac(int n)
{
return mreturn<cont>(fac_state{n,1})>>=fac_impl;
}
int main()
{
auto f=fac(5);
std::cout<<"running f\n";
auto r=f.run().res;
std::cout<<"fac(5)="<<r<<"\n";
}