Created
April 4, 2024 00:50
-
-
Save blvrd/39298611c0ffb61531ffe8753b3c33d0 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
# Here's a simple lisp expression parser that generates | |
# an abstract syntax tree in the form of nested arrays | |
def tokenize(lisp_expression) | |
lisp_expression.gsub("(", " ( ").gsub(")", " ) ").split(" ") | |
end | |
def parse(tokens) | |
raise "No tokens to parse" if tokens.empty? | |
token = tokens.shift | |
if token == "(" | |
list = [] | |
while tokens[0] != ")" | |
list << parse(tokens) | |
end | |
tokens.shift | |
list | |
else | |
atom(token) | |
end | |
end | |
# an atom is "atomic" in that in can't be split up any further. | |
# We turn it into one of two concrete types: integer or symbol. | |
def atom(token) | |
begin | |
Integer(token) | |
rescue ArgumentError | |
token.to_sym | |
end | |
end | |
def evaluate(expression) | |
# We'll implement this together! | |
end | |
lisp_expression = "(first (list 1 (+ 2 3) 9))" | |
tokens = tokenize(lisp_expression) | |
parsed_expression = parse(tokens) | |
print parsed_expression |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment