-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlist_example.py
More file actions
31 lines (26 loc) · 802 Bytes
/
list_example.py
File metadata and controls
31 lines (26 loc) · 802 Bytes
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
from do_notation import with_do_notation
import itertools
# instance Monad [] where
# return x = [x]
# xs >>= f = [y | x <- xs, y <- f x]
class ListMonad(object):
def __init__(self, lst):
self.lst = lst
def bind(self, f):
return ListMonad(list(itertools.chain(*[f(x).lst for x in self.lst])))
@staticmethod
def mreturn(x):
return ListMonad([x])
def __repr__(self):
return 'ListMonad({})'.format(self.lst)
@with_do_notation
def list_example():
list1 = ListMonad([1,2,3])
list2 = ListMonad([-1,2])
with do(ListMonad) as z:
x = list1
y = list2
mreturn(x*y)
assert(sorted(z.lst) == sorted([x*y for x in list1.lst for y in list2.lst]))
return z
print list_example() # ListMonad([-1, 2, -2, 4, -3, 6])