This repository has been archived by the owner on Feb 21, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmonads.py
227 lines (148 loc) · 4.79 KB
/
monads.py
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import inspect
import collections
# BASIC API
def do(*actions):
return reduce(lambda c, n: n.bind(c), reversed(actions))
def mreturn(l):
return MReturn(l)
# MONADS THEMSELVES
class Monad(object):
# Implement these please:
@staticmethod
def mreturn(v):
"""a -> M a"""
raise NotImplementedError
def bind(self, f):
"""
M a -> (value -> context -> M b) -> M b
please take a look on List and Maybe implementations"""
raise NotImplementedError
def run(self, context={}):
"""
M a -> a
please call self.apply(context) and then modify the result
"""
raise NotImplementedError
# Utils
def __init__(self, it):
self.it = it
def __neg__(self):
return PrepareBinding(self)
def __call__(self, _, context):
return self.apply(context)
def apply(self, context):
context['_monad'] = self.__class__
return lambda_context_call(self.it, context)
class List(Monad):
@staticmethod
def mreturn(v):
return [v]
def bind(self, f):
def bound(**ct):
for i in self.apply(ct):
for j in f(i, ct):
yield j
return List( bound )
def run(self, context={}):
return list(self.apply(context))
class Maybe(Monad):
@staticmethod
def mreturn(v):
return (True, v)
def bind(self, f):
def bound(**ct):
t, v = self.apply(ct)
if not t:
return (False, False)
else:
return f(v, ct)
return Maybe( bound )
def run(self, context={}):
return self.apply(context)
class Probability(Monad):
@staticmethod
def mreturn(v):
return [(v, 1)]
def bind(self, f):
def bound(**ct):
# can't do lazily (dont know how)
nexts = []
for val1, prob1 in self.apply(ct):
for val2, prob2 in f(val1, ct):
nexts.append( (val2, prob1 * prob2) )
print "nexts: ", nexts
return nexts
return Probability( bound )
def run(self, context={}):
d = collections.defaultdict(int)
for v, p in self.apply(context):
d[v] += p
return d.items()
# MONADIC FUNCTIONS
def guard(l):
def guard_it(**kwargs):
if lambda_context_call(l, kwargs):
yield None
return HelperMonad(guard_it)
def tests():
r = [ Var('a') <- List(lambda ct: [1, 2, 3]),
Var('b') <- List(lambda ct: [1, 2, 3]),
MReturn(List, lambda a, b: (a, b) ) ]
print list(RunList(r).apply({}))
r = [ Var('a') <- List(lambda ct: [1, 2, 3]),
Var('b') <- List(lambda ct: [ct['a'] * 10, ct['a'] * 50]),
# MGuard(List, lambda ct: ct['b'] < 100),
MReturn(List, lambda a, b: (a, b) ) ]
print list(RunList(r).apply({}))
r = [ Var('a') <- Maybe(lambda ct: (True, 7)),
Var('b') <- Maybe(lambda ct: (True, 123)),
MReturn(Maybe, lambda a, b: (b, a) ) ]
print RunList(r).apply({})
r = [ Var('a') <- Maybe(lambda ct: (True, 7)),
Var('b') <- Maybe(lambda ct: (False, False)),
Var('c') <- Maybe(lambda ct: 123 / 0),
MReturn(Maybe, lambda a, c: (c, a) ) ]
print RunList(r).apply({})
# UTILS
class Var(object):
def __init__(self, name):
self.name = name
def __lt__(self, mb):
return BindName(self.name, mb.m)
class PrepareBinding(object):
def __init__(self, m):
self.m = m
class BindName(object):
def __init__(self, name, fr):
self.name = name
self.fr = fr
def bind(self, to):
def f(v, context):
""" value -> monad """
new_context = dict(context)
new_context[self.name] = v
return to.apply(new_context)
return self.fr.bind(f)
class HelperMonad(Monad):
def apply(self, context):
return lambda_context_call(self.it, context)
def bind(self, f):
def bound(**ct):
for j in self.apply(ct):
for i in f(None, ct):
yield i
return HelperMonad( bound )
class MReturn(HelperMonad):
def __init__(self, l):
self.l = l
def apply(self, context):
val = lambda_context_call(self.l, context)
return context['_monad'].mreturn( val )
def lambda_context_call(l, context):
sp = inspect.getargspec(l)
if sp.keywords:
return l(**context)
else:
args = dict((k, v) for k, v in context.iteritems()
if k in sp.args)
return l(**args)