Skip to content

Instantly share code, notes, and snippets.

@spitz-dan-l
Last active August 29, 2015 14:04
Show Gist options
  • Save spitz-dan-l/c8f69e4a045f6f57f2f0 to your computer and use it in GitHub Desktop.
Save spitz-dan-l/c8f69e4a045f6f57f2f0 to your computer and use it in GitHub Desktop.
Python List Monad with Coroutine Copying
# 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