Created
October 28, 2021 05:14
-
-
Save akgerber/6a27e99dc9dec063fee9e382e3383ce4 to your computer and use it in GitHub Desktop.
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
# Python 3.10 required for pattern matching | |
from typing import List | |
def parse_args(argstr: str) -> List: | |
args = [] | |
arg = [] | |
parendepth = 0 | |
for c in argstr: | |
match c: | |
case " ": | |
if parendepth == 0: | |
args.append("".join(arg)) | |
arg = [] | |
else: | |
arg.append(c) | |
case "(": | |
parendepth += 1 | |
arg.append(c) | |
case ")": | |
parendepth -= 1 | |
arg.append(c) | |
case _: | |
arg.append(c) | |
if len(arg) > 0: | |
args.append("".join(arg)) | |
return args | |
def lisp_parser(lisp: str) -> List: | |
if lisp.isnumeric(): | |
return int(lisp) | |
l, _, r = lisp.partition(" ") | |
match list(l): | |
case ["(", *func]: | |
if r[-1] != ')': | |
raise ValueError | |
argstr = r[:-1] | |
parsedargs = list(map(lisp_parser, parse_args(argstr))) | |
return ["".join(func)] + parsedargs | |
case _: | |
raise ValueError | |
if __name__ == "__main__": | |
print(lisp_parser(input())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment