Skip to content

Instantly share code, notes, and snippets.

@LennaHammer
Created April 29, 2023 04:30
Show Gist options
  • Save LennaHammer/833f861b6b336021a217e815154033f6 to your computer and use it in GitHub Desktop.
Save LennaHammer/833f861b6b336021a217e815154033f6 to your computer and use it in GitHub Desktop.
class SexpParser
def initialize
@tokens = []
end
def parse_list
xs = []
xs << parse_atom until @tokens.fetch(0) == :')'
@tokens.shift
xs
end
def parse_atom
x = @tokens.shift
x == :'(' ? parse_list : x
end
def parse(text)
@tokens = text.scan(/[()]|[^()\s]+/)
@tokens.map! { |x| x =~ /\A\d+\z/ ? x.to_i : x.to_sym }
# p @tokens
parse_atom
end
end
parser = SexpParser.new
p parser.parse '(+ (- a b) c)'
p parser.parse '(define (f x) (+ x 1))'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment