Entry tags:
(no subject)
Realized today that you can write the
parse function from my earlier post in a much simpler way using iterators and recursion:Expr = t.Union[str, t.Tuple['Expr']]
def parse(tokens: t.Iterable[str]) -> t.Iterator[Expr]:
"""Parse an iterable of Lisp tokens.
Unmatched parentheses will be ignored.
>>> tuple(parse(lex('a (b (c d))')))
('a', ('b', ('c', 'd')))
>>> tuple(parse(lex('((a b) c (d e))')))
((('a', 'b'), 'c', ('d', 'e')),)
>>> tuple(parse(lex('(a (b)')))
(('a', ('b',)),)
>>> tuple(parse(lex('a)(')))
('a',)
"""
for token in tokens:
if token == ')':
return
elif token == '(':
yield tuple(parse(tokens))
else:
yield token