Skip to content

Instantly share code, notes, and snippets.

@seantalts
Created May 4, 2016 18:40
Show Gist options
  • Save seantalts/15c8a64f8ed339216d7e3f8d72ca38a1 to your computer and use it in GitHub Desktop.
Save seantalts/15c8a64f8ed339216d7e3f8d72ca38a1 to your computer and use it in GitHub Desktop.
small terrible lisp ast parser
import re
def lex(s):
return re.findall("(\(|\)|[\w\*\+\-]+)", s)
def get_ast(tokens):
ast = []
while tokens:
t = tokens.pop(0)
if t == '(':
while t != ')' and tokens:
ast.append(get_ast(tokens))
elif t == ')':
break
else:
if t.isdigit():
ast.append(float(t))
else:
ast.append(t)
if not ast:
raise SyntaxError("idk dude")
return ast
print get_ast(lex("(+ (* 2 4) 3)"))
# => [['+', ['*', 2.0, 4.0], [3.0]]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment