Created
April 18, 2017 02:35
-
-
Save jrraymond/5d4df56e2f9374e9c030e7ad54329d2c to your computer and use it in GitHub Desktop.
lisp parser
This file contains hidden or 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 lex(inp): | |
tkns = list() | |
acc = list() | |
for ch in inp: | |
if ch.isspace() and acc: | |
tkns.append(''.join(acc)) | |
acc = list() | |
elif ch == '(' or ch == ')': | |
if acc: | |
tkns.append(''.join(acc)) | |
acc = list() | |
tkns.append(ch) | |
elif not ch.isspace(): | |
acc.append(ch) | |
if acc: | |
tkns.append(''.join(acc)) | |
return tkns | |
def parse(tkns): | |
exps = list() | |
while tkns: | |
if tkns[0] == ')': | |
break | |
elif tkns[0] == '(': | |
e, tkns = parse(tkns[1:]) | |
if not tkns or tkns[0] != ')': | |
raise Exception("Expected ')'") | |
exps.append(e if len(e) != 1 else e[0]) | |
else: | |
exps.append(tkns[0]) | |
tkns = tkns[1:] | |
return exps, tkns | |
def parse(inp): | |
return parse(lex(inp))[0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment