forked from siddhi/python-functional
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonads.py
More file actions
50 lines (36 loc) · 1.06 KB
/
Copy pathmonads.py
File metadata and controls
50 lines (36 loc) · 1.06 KB
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
from itertools import chain
class Nothing:
def map(self, fn):
return Nothing()
def flatmap(self, fn):
return Nothing()
def __str__(self):
return 'Nothing()'
class Just:
def __init__(self, val):
self.val = val
def map(self, fn):
return Just(fn(self.val))
def flatmap(self, fn):
return fn(self.val)
def __str__(self):
return f'Just({self.val})'
class MultiValue:
def __init__(self, values):
self.values = set(values)
def map(self, fn):
out = {fn(val) for val in self.values}
return MultiValue(out)
def flatmap(self, fn):
out = (fn(val).values for val in self.values)
return MultiValue(chain(*out))
def __add__(self, other):
match other:
case MultiValue():
return self.flatmap(lambda a: a + other)
case _:
return self.map(lambda a: a + other)
def __radd__(self, other):
return self + other
def __repr__(self):
return f'MultiValue({self.values})'