Skip to content

Instantly share code, notes, and snippets.

@fduxiao
Last active June 10, 2017 07:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fduxiao/d5a81b5e5eb8fad687f130ef98990e18 to your computer and use it in GitHub Desktop.
Save fduxiao/d5a81b5e5eb8fad687f130ef98990e18 to your computer and use it in GitHub Desktop.
python used with functional programming
#!/usr/bin/env python3
class Chain:
cal = None
def __init__(self):
self.cal = lambda x: x
def chain(self, f):
old = self.cal
def cal(x):
return f(old(x))
self.cal = cal
return f # we don't f to be nothing
c = Chain()
@c.chain
def try1(a):
return a+1
print(c.cal(0))
@c.chain
def try2(a):
return a+2
print(c.cal(3))
#!/usr/bin/env python3
class Monad:
def __init__(self):
pass
@staticmethod
def ret(x):
pass
def bind(self, f):
pass
def run(self):
pass
class Maybe(Monad):
Nothing = 0
Just = 1
def __init__(self, a=None):
super(Maybe, self).__init__()
self.data = None
if a is None:
self.state = Maybe.Nothing
else:
self.data = a
self.state = Maybe.Just
@staticmethod
def just(x):
return Maybe(x)
@staticmethod
def nothing():
return Maybe()
@staticmethod
def ret(x):
return Maybe.just(x)
def bind(self, f):
if self.state == self.Nothing:
return
else:
new_maybe = f(self.data)
self.__dict__ = new_maybe.__dict__
test1 = Maybe.just(0)
@test1.bind
def try1(x):
return Maybe.ret(x + 1)
print(1, test1.data)
@test1.bind
def try2(_):
return Maybe.nothing()
print(2, test1.data)
@test1.bind
def try3(x):
return Maybe.ret(x + 2)
print(3, test1.data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment