Last active
July 28, 2018 18:00
-
-
Save dovinmu/bcab247b063cd3e294e57d06440268a1 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
# https://gist.github.com/dovinmu/bcab247b063cd3e294e57d06440268a1 | |
def popParens(s): | |
return s[s.find('(')+1:s.rfind(')')] | |
def getArgs(s): | |
def appendArg(arg): | |
if '(' in arg: | |
args.append(getArgs(arg.strip())) | |
else: | |
try: | |
number = float(arg.strip()) | |
if '.' in arg: | |
args.append(number) | |
else: | |
args.append(int(number)) | |
except: | |
args.append(arg.strip()) | |
s = popParens(s) | |
args = [] | |
charIdx = 0 | |
parenDepth = 0 | |
inQuote = False | |
for i in range(len(s)): | |
if s[i] == '"': | |
inQuote = not inQuote | |
if inQuote: | |
continue | |
if s[i] == '(': | |
parenDepth += 1 | |
elif s[i] == ')': | |
parenDepth -= 1 | |
if parenDepth == 0: | |
if s[i] == ' ' and s[charIdx:i].strip() != '': | |
appendArg(s[charIdx:i]) | |
charIdx = i | |
appendArg(s[charIdx:]) | |
return args | |
def testAST(): | |
s='(first (list 1 (+ 2 3) 9))' | |
print(getArgs(s)) | |
s='(first "Hello World")' | |
print(getArgs(s)) | |
s='(first (list "asdf fdsa" (+ 2 3) 9.2))' | |
print(getArgs(s)) | |
s='''(defun factorial (n) | |
(if (= n 0) 1 | |
(* n (factorial (- n 1)))))''' | |
print(getArgs(s)) | |
s='''(defun -reverse (list) | |
(let ((return-value '())) | |
(dolist (e list) (push e return-value)) | |
return-value))''' | |
print(getArgs(s)) | |
if __name__ == "__main__": | |
testAST() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment