Created
April 9, 2018 13:32
-
-
Save nemesiscodex/8de4fd00da53d1b785bf3cb4b413ddf7 to your computer and use it in GitHub Desktop.
Python monad test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Maybe(): | |
def __init__(self, value): | |
self.value = value | |
def empty(): | |
return Maybe(None) | |
def of(value): | |
return Maybe(value) | |
def map(self, f): | |
if self.value: | |
return Maybe.of(f(self.value)) | |
return Maybe.empty() | |
def filter(self, f): | |
if f(self.value): | |
return Maybe.of(self.value) | |
return Maybe.empty() | |
def flat_map(self, f): | |
if self.value: | |
return f(self.value) | |
return Maybe.empty() | |
def get(self): | |
return self.value | |
def if_present(self, f): | |
if self.value: | |
f(self.value) | |
def or_else(self, value): | |
if self.value: | |
return self.value | |
return value | |
def liff(self, b, f): | |
return self.flat_map(lambda x: b.map(lambda y: f(x,y))) | |
class List(): | |
def __init__(self, *args): | |
if len(args) == 1: | |
if args[0]: | |
self.value = tuple(args[0]) | |
else: | |
self.value = () | |
else: | |
self.value = args | |
def of(self, *args): | |
return List(args) | |
def empty(): | |
return List(None) | |
def map(self, f): | |
if self.value: | |
return List(tuple(map(f, self.value))) | |
else: | |
return List.empty() | |
def filter(self, f): | |
if self.value: | |
return List(tuple(filter(f, self.value))) | |
else: | |
return List.empty() | |
def if_present(self, f): | |
if self.value: | |
return f(self.value) | |
List \ | |
.of(1,2,3,4,5,6) \ | |
.map(lambda x : x * 100) \ | |
.filter(lambda x: x % 13 == 0) \ | |
.if_present(print) | |
Maybe \ | |
.of(87) \ | |
.map(lambda x: x*2) \ | |
.liff(Maybe.of(5), lambda x,y: x*y) \ | |
.filter(lambda x: x % 5 == 0 and x % 2 == 0) \ | |
.if_present(print) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment