Last active
December 14, 2015 06:18
-
-
Save lucian1900/5041118 to your computer and use it in GitHub Desktop.
This file contains 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
from __future__ import print_function | |
from operator import add, mul | |
from functools import partial | |
class Monad(object): | |
def __init__(self, value): | |
self._value = value | |
def bind(self, fn): | |
raise NotImplementedError('Must implement bind') | |
@classmethod | |
def lift(cls, fn): | |
def wrapper(value): | |
return cls(cls(value).bind(fn)) | |
return wrapper | |
class Identity(Monad): | |
def bind(self, fn): | |
return fn(self._value) | |
class Maybe(Monad): | |
def bind(self, fn): | |
if self._value == None: | |
return self | |
else: | |
return fn(self._value) | |
if __name__ == '__main__': | |
mprint = Identity.lift(print) | |
Identity('hello').bind(mprint) | |
minc = Maybe.lift(partial(add, 1)) | |
mdouble = Maybe.lift(partial(mul, 2)) | |
mnone = Maybe.lift(lambda x: None) | |
mprint = Maybe.lift(print) | |
Maybe(1).bind(minc).bind(mdouble).bind(mprint) | |
Maybe(1).bind(mnone).bind(minc).bind(mprint) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment