Skip to content

Instantly share code, notes, and snippets.

@nicolashahn
Created March 6, 2018 08:12
Show Gist options
  • Save nicolashahn/9f9456f6ebee1cc83b5a0d42cdee6687 to your computer and use it in GitHub Desktop.
Save nicolashahn/9f9456f6ebee1cc83b5a0d42cdee6687 to your computer and use it in GitHub Desktop.
lisp parser
def token_to_atom(token):
''' ints, floats converted, everything else string '''
if token[0] in '1234567890':
if '.' in token:
return float(token)
return int(token)
return token
def tokens_to_tree(tokens):
''' take out parens, nest lists '''
res = []
while tokens:
t = tokens.pop(0)
if t == ')':
return res
elif t == '(':
res.append(tokens_to_tree(tokens))
else:
res.append(token_to_atom(t))
return res[0]
def parse(code):
tokens = (code.
replace('(', ' ( ').
replace(')', ' ) ').
split())
return tokens_to_tree(tokens)
code = '(first (list 1 (+ 2 3) 9))'
result = ['first', ['list', 1, ['+', 2, 3], 9]]
assert parse(code) == result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment