Skip to content

Instantly share code, notes, and snippets.

@russolsen
Created January 26, 2012 20:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save russolsen/1684926 to your computer and use it in GitHub Desktop.
Save russolsen/1684926 to your computer and use it in GitHub Desktop.
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