Created
August 27, 2020 15:34
-
-
Save dpiponi/5ee0c535c6f60bf80b11ed63c4cce974 to your computer and use it in GitHub Desktop.
Are these runners?
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
# Python 3 | |
import collections | |
Write = collections.namedtuple("Write", ["written"]) | |
def hello_world(): | |
yield Write("Hello, world!") | |
yield Write("Hello, world!") | |
return 1 | |
def identity(gen): | |
try: | |
e = next(gen) | |
raise ValueError("Fatal Exception") | |
except StopIteration as r: | |
return r.value | |
def run_write(fh, gen): | |
try: | |
e = next(gen) | |
while True: | |
if isinstance(e, Write): | |
fh.write(e.written) | |
e = next(gen) | |
else: | |
e = gen.send((yield e)) | |
except StopIteration as r: | |
fh.close() | |
return r.value | |
def run_accumulate_write(acc, gen): | |
try: | |
e = next(gen) | |
while True: | |
if isinstance(e, Write): | |
acc += e.written | |
e = next(gen) | |
else: | |
e = gen.send((yield e)) | |
except StopIteration as r: | |
yield Write(acc) | |
return r.value | |
print(identity( | |
run_write(open("hello.txt", "w"), hello_world()))) | |
# Check contents | |
with open("hello.txt", "r") as fh: | |
print(fh.read()) | |
print( | |
identity( | |
run_write(open("hello.txt", "w"), | |
run_accumulate_write("", hello_world())))) | |
# Check contents | |
with open("hello.txt", "r") as fh: | |
print(fh.read()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment