Created
June 26, 2017 13:47
-
-
Save joedougherty/58f1d039fd3fda79f075c8b2312e4e32 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
| """ Generator-based versions of tokenize and read_from_tokens from Norving's "How to write a Lisp Interpreter in Python" """ | |
| from itertools import takewhile | |
| def tokenize(chars): | |
| ''' Convert a string expression into a generator of tokens. ''' | |
| return (t for t in chars.replace('(', ' ( ').replace(')', ' ) ').split()) | |
| def read_from_tokens_gen(tokens, current_token=None): | |
| if current_token: | |
| token = current_token | |
| else: | |
| token = next(tokens) | |
| if token == '(': | |
| L = [] | |
| for t in takewhile(lambda x: x != ')', tokens): | |
| L.append(read_from_tokens_gen(tokens, current_token=t)) | |
| return L | |
| elif token == ')': | |
| raise SyntaxError('unexpected )') | |
| else: | |
| return token |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment