Skip to content

Instantly share code, notes, and snippets.

@nakamuray
Created January 3, 2013 14:51
Show Gist options
  • Save nakamuray/4443997 to your computer and use it in GitHub Desktop.
Save nakamuray/4443997 to your computer and use it in GitHub Desktop.
python の decorator と generator で maybe monad みたいなの。 最後に yield した値が関数を置き換える。 None が yield されたらその場で終わり。 decorator が関数を返さないという最低にキモいことをしているので、実用性はない。
def maybe(gen):
it = gen()
v = next(it)
try:
while v is not None:
v = it.send(v)
except StopIteration:
return v
def test():
@maybe
def result():
x = yield 1
y = yield x * 2
yield y * 3
assert result == 6
@maybe
def result():
x = yield None
y = yield x * 2
yield y * 3
assert result is None
if __name__ == '__main__':
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment