-
Notifications
You must be signed in to change notification settings - Fork 10
/
list6.cpp
115 lines (100 loc) · 2.38 KB
/
list6.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include <iostream>
#include <list>
#include <utility>
#include <type_traits>
template<typename T,typename Q>
std::ostream& operator<<(std::ostream& os,const std::pair<T,Q>& p)
{
return os<<"["<<p.first<<","<<p.second<<"]";
}
template<typename T>
std::ostream& operator<<(std::ostream& os,const std::list<T>& l)
{
os<<"[";
for(const auto& x:l)os<<x<<" ";
os<<"]";
return os;
}
template<typename T>
struct list:std::list<T>
{
using base=std::list<T>;
using base::base;
list(const T& x):base(1,x){} // compatibility with mreturn
};
list<int> decinc(int x)
{
return {x-1,x+1};
}
template<template<typename> class M,typename T>
M<T> mreturn(const T& x)
{
return x;
}
template<typename T,typename F>
auto operator>>=(const list<T>& l, F f)
{
decltype(f(std::declval<T>())) ret={};
for(const auto& t:l)ret.splice(ret.end(),f(t));
return std::move(ret);
}
#define DO(var,monad,body) \
((monad)>>=[=](const auto& var){ \
return body; \
})
template<typename Pred>
auto filter(Pred pred)
{
return [=](const auto& x){
return pred(x)?
mreturn<list>(x):
list<std::remove_cv_t<std::remove_reference_t<decltype(x)>>>{};
};
}
int main()
{
// {x+y | x <- [0 1 2], y <- [1 2 3], even (x+y)}, without filter helper
std::cout<<
DO(x,list<int>({0,1,2}),
DO(y,list<int>({1,2,3}),
(x+y)%2==0?mreturn<list>(x+y):list<int>{}
))
<<"\n";
auto even=[](const auto& n){return n%2==0;};
// {x+y | x <- [0 1 2], y <- [1 2 3], even (x+y)}, with filter helper
std::cout<<
DO(x,list<int>({0,1,2}),
DO(y,list<int>({1,2,3}),
filter(even)(x+y)
))
<<"\n";
// {x+y | x <- [0 1 2], even x, y <- [1 2 3]}
std::cout<<
DO(x,list<int>({0,1,2})>>=filter(even),
DO(y,list<int>({1,2,3}),
mreturn<list>(x+y)
))
<<"\n";
// {x+y | x <- [0 1 2], y <- [1 2 3], even y}
std::cout<<
DO(x,list<int>({0,1,2}),
DO(y,list<int>({1,2,3})>>=filter(even),
mreturn<list>(x+y)
))
<<"\n";
// {(x,y) | x <- [0 1 2], y <- [1 2 3]}
std::cout<<
DO(x,list<int>({0,1,2}),
DO(y,list<int>({1,2,3}),
mreturn<list>(std::make_pair(x,y))
))
<<"\n";
// {(x,y) | x <- [0 1 2], y <- [1 2 3], (even x) || (even y)}
std::cout<<
DO(x,list<int>({0,1,2}),
DO(y,list<int>({1,2,3}),
filter([=](const auto&){return (x%2==0)||((y%2==0));})
(std::make_pair(x,y))
))
<<"\n";
}