Created
January 26, 2012 20:31
-
-
Save russolsen/1684926 to your computer and use it in GitHub Desktop.
An S expression (i.e. LISP) parser in 32 lines of Ruby.
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
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