Last active
August 29, 2015 14:04
-
-
Save spitz-dan-l/c8f69e4a045f6f57f2f0 to your computer and use it in GitHub Desktop.
Python List Monad with Coroutine Copying
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
# how to get python to look like this haskell?.. | |
# listOfTuples :: [(Int,Char)] | |
# listOfTuples = do | |
# n <- [1,2] | |
# ch <- ['a','b'] | |
# return (n,ch) | |
# -> [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')] | |
# ..such that we can write a coroutine and apply a decorator that will make | |
@list_monad | |
def list_of_tuples(): | |
n = yield [1, 2] | |
ch = yield ['a', 'b'] | |
return (n, ch) | |
# -> [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')] | |
def list_monad(generator): | |
@wraps(generator) | |
def inner(*args, **kwds): | |
def inner2(gen = None, objs = (None,)): | |
if gen is None: | |
gen = generator(*args, **kwds) | |
for obj in objs: | |
g = gen.copy() # if only... this is required but is not supported :( | |
try: | |
lst_monad = g.send(obj) # perhaps implicitly lift stuff here? | |
except StopIteration as s: | |
yield s.value | |
else: | |
yield from inner2(g, lst_monad) | |
return inner2() | |
return inner | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment