Skip to content

Instantly share code, notes, and snippets.

@blvrd
Created April 4, 2024 00:50
Show Gist options
  • Save blvrd/39298611c0ffb61531ffe8753b3c33d0 to your computer and use it in GitHub Desktop.
Save blvrd/39298611c0ffb61531ffe8753b3c33d0 to your computer and use it in GitHub Desktop.
# 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