housecarpenter: A drawing of Bob Dylan singing into a microphone with white make-up on his face. (Default)
[personal profile] housecarpenter
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

Profile

housecarpenter: A drawing of Bob Dylan singing into a microphone with white make-up on his face. (Default)
housecarpenter

April 2019

S M T W T F S
 123456
78910111213
14151617181920
21222324252627
2829 30    

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Feb. 12th, 2026 06:25 am
Powered by Dreamwidth Studios