Skip to content

Instantly share code, notes, and snippets.

@jpvelez
Created January 22, 2020 20:34
Show Gist options
  • Save jpvelez/ecd02e6c41d3932216e26d17de030704 to your computer and use it in GitHub Desktop.
Save jpvelez/ecd02e6c41d3932216e26d17de030704 to your computer and use it in GitHub Desktop.
def add_token(ast, token):
if token != "":
ast.append(token)
return ast, ""
def parse_list(code, i):
ast = []
current_token = ""
while i < len(code):
char = code[i]
i += 1
if char == "(":
sublist, i = parse_list(code, i)
ast.append(sublist)
elif char == ")":
ast, current_token = add_token(ast, current_token)
return ast, i
elif char == " ":
ast, current_token = add_token(ast, current_token)
else:
current_token += char
def parser(code):
ast, i = parse_list(code, 1)
return ast
code = "(first (list 1 (+ 2 3) 9))"
ast = parser(code)
ast == ['first', ['list', '1', ['+', '2', '3'], '9']]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment