-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaybe.py
More file actions
28 lines (20 loc) · 710 Bytes
/
maybe.py
File metadata and controls
28 lines (20 loc) · 710 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
from functor import Functor
class Maybe(Functor):
def __init__(self, value):
super(Maybe, self).__init__(value)
@staticmethod
def of(value):
return Maybe(value)
def map(self, fn):
if self._value is None:
return Maybe(None)
else:
return Maybe(fn(self._value))
def main():
print(Maybe.of(None).map(lambda x: x + 1)) # Maybe(None)
print(Maybe.of(None).map(lambda x: x * x)) # Maybe(None)
print(Maybe.of(0).map(lambda x: x + 1)) # Maybe(1)
print(Maybe.of(99).map(lambda x: x + 1)) # Maybe(100)
print(Maybe.of(99).map(lambda x: x + 1).map(lambda x: x * x)) # Maybe(10000)
if __name__ == "__main__":
main()