Created
April 6, 2019 01:56
-
-
Save TomLisankie/8530db8fec0c4ce1ec31a428e53d9b7b 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
lisp = input("Enter your Lisp code: ") | |
# splits Lisp expression into tokens and strips them of whitespace. | |
def makeTokens(lisp): | |
lispTokens = lisp.replace("(", " ( ").replace(")", " ) ").split() | |
return [token.strip() for token in lispTokens] | |
# if the token is a number, return it as the appropriate type (int or float). | |
# otherwise, return it as a string | |
def createAtom(token): | |
try: | |
return int(token) | |
except: | |
try: | |
return float(token) | |
except: | |
return str(token) | |
def makeAST(lispTokens): | |
if len(lispTokens) == 0: | |
return "You need to have some text!" | |
currentToken = lispTokens.pop(0) | |
if currentToken == "(": # beginning of a new expression | |
newExpressionList = [] | |
while lispTokens[0] != ")": # put everything in the form into a list | |
newExpressionList.append(makeAST(lispTokens)) | |
lispTokens.pop(0) | |
return newExpressionList | |
else: # if the token is an atom, return the atom | |
return createAtom(currentToken) | |
tokens = makeTokens(lisp) | |
ast = makeAST(tokens) | |
print(ast) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment