Created
January 3, 2013 14:51
-
-
Save nakamuray/4443997 to your computer and use it in GitHub Desktop.
python の decorator と generator で maybe monad みたいなの。
最後に yield した値が関数を置き換える。 None が yield されたらその場で終わり。
decorator が関数を返さないという最低にキモいことをしているので、実用性はない。
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
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