Skip to content

Instantly share code, notes, and snippets.

@TomLisankie
Created April 6, 2019 01:56
Show Gist options
  • Save TomLisankie/8530db8fec0c4ce1ec31a428e53d9b7b to your computer and use it in GitHub Desktop.
Save TomLisankie/8530db8fec0c4ce1ec31a428e53d9b7b to your computer and use it in GitHub Desktop.
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