Created
January 22, 2020 20:34
-
-
Save jpvelez/ecd02e6c41d3932216e26d17de030704 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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