Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An S expression (i.e. LISP) parser in 32 lines of Ruby.
class SExpressionParser
def initialize(expression)
@tokens = expression.scan /[()]|\w+|".*?"|'.*?'/
end
def peek
@tokens.first
end
def next_token
@tokens.shift
end
def parse
if (token = next_token) == '('
parse_list
elsif token =~ /['"].*/
token[1..-2]
elsif token =~ /\d+/
token.to_i
else
token.to_sym
end
end
def parse_list
list = []
list << parse until peek == ')'
next_token
list
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment