Skip to content

Instantly share code, notes, and snippets.

@zed
Created October 15, 2011 23:06
Show Gist options
  • Select an option

  • Save zed/1290292 to your computer and use it in GitHub Desktop.

Select an option

Save zed/1290292 to your computer and use it in GitHub Desktop.
Translation of "Coroutines in C" in Python
#!/usr/bin/env python
"""Translation of "Coroutines in C" in Python
http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
"""
EOF = b''
def decompressor(getchar):
for c in iter(getchar, EOF):
if c == 0xFF:
len = getchar()
c = getchar();
for _ in xrange(len):
yield c
else:
yield c
yield EOF
def parser(getchar):
for c in iter(getchar, EOF):
if isalpha(c):
while 1:
add_to_token(c)
c = getchar()
if not isalpha(c):
got_token(WORD)
break
#NOTE: fall-through as in C code (even if EOF)
add_to_token(c)
got_token(PUNCT)
#USAGE: parser(iter(decompressor(lambda: sys.stdin.read(1)).next)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment