Last active
August 29, 2015 14:18
-
-
Save sir-wabbit/e15ea9762a58935b28f2 to your computer and use it in GitHub Desktop.
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
| from collections import namedtuple | |
| PutStrLn = namedtuple('PutStrLn', 'value') | |
| Read = namedtuple('Read', []) | |
| def hello(): | |
| _ = yield PutStrLn('Hello.') | |
| return True | |
| def f(myname): | |
| status = yield from hello() | |
| _ = yield PutStrLn('What\'s your name?') | |
| name = yield Read() | |
| _ = yield PutStrLn('Nice to meet you, ' + name + '. I am ' + myname + '.') | |
| return status | |
| def runIO(it): | |
| try: | |
| request = it.__next__() | |
| while True: | |
| if isinstance(request, PutStrLn): | |
| print(request.value) | |
| request = it.send(True) | |
| elif isinstance(request, Read): | |
| request = it.send(input()) | |
| else: | |
| raise NotImplementedError('Unknown request.') | |
| except StopIteration as s: | |
| return s.value | |
| runIO(f('Jack')) | |
| def runE(effects): | |
| def run0(it): | |
| output_lines = [] | |
| try: | |
| request = it.__next__() | |
| while True: | |
| for cls, handler in effects: | |
| if isinstance(request, cls): | |
| result = handler(request) | |
| request = it.send(result) | |
| break | |
| else: | |
| raise NotImplementedError('Unknown request.') | |
| except StopIteration as s: | |
| return s.value | |
| return run0 | |
| # runIO can be defined in terms of runE | |
| runIO = runE([(PutStrLn, lambda r: print(r.value)), | |
| (Read, lambda r: input())]) | |
| runIO(f('abc')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment