Inverse parentheses
kellett.im·6d·
🐻Polars
Preview
Report Post

Have you ever noticed that lots of programming languages let you use parentheses to group operands, but none use them to ungroup them? No? Well let’s pretend this is a normal thing to be thinking about, and see what we can do about it.

Grouping with parentheses is relatively easy to add to a language grammar. The rule that accepts atomic things like 37 simply needs to also accept an opening paren,1 at which point it will recursively parse an entire expression, and then eat a closing paren.

def parse_atom(lex):
r = next(lex)
if r[0] == 'integer':
return int(r[1])
elif r[0] == '(':
expr = parse_expr(lex)
s = next(lex)
if s[0] != ')':
raise ParseError("missing close paren")
return expr
else:
raise ParseError(f"unexpected {r[0]}")

Anti-grouping isn’t quite as str…

Similar Posts

Loading similar posts...