Skip to content

Instantly share code, notes, and snippets.

@shelling
Created September 24, 2013 05:35
Show Gist options
  • Select an option

  • Save shelling/6680747 to your computer and use it in GitHub Desktop.

Select an option

Save shelling/6680747 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
$:.unshift(".")
require "treetop"
require "lisp"
require "pp"
pp LispParser.new.parse("1.1").calculate
pp LispParser.new.parse("( )").calculate
pp LispParser.new.parse("(+)").calculate
pp LispParser.new.parse("(-)").calculate
pp LispParser.new.parse("(*)").calculate
pp LispParser.new.parse("(/)").calculate
pp LispParser.new.parse("(+ 4 3 2 1)").calculate
pp LispParser.new.parse("(- 4 3 2 1)").calculate
pp LispParser.new.parse("(* 4 3 2 1)").calculate
pp LispParser.new.parse("(/ 4 3 2 1)").calculate
pp LispParser.new.parse("(/ (* 5 (+ 5 5)) 5)").calculate
grammar Lisp
rule top
evalable* {
def calculate
elements.first.calculate
end
}
end
rule evalable
sexp / value
end
rule value
float / integer
end
rule float
[+-]? [0-9]* "." [0-9]* {
def calculate
text_value.to_f
end
}
end
rule integer
[+-]? [0-9]+ {
def calculate
text_value.to_i
end
}
end
rule symbol
( "+" / "-" / "*" / "/" ) {
def calculate
text_value.to_sym
end
}
end
rule sexp
"(" space function:symbol space list:(space evalable)* space ")" {
def calculate
list.elements.map(&:evalable).map(&:calculate).inject(function.calculate)
end
}
/
"(" space ")" {
def calculate
nil
end
}
end
rule space
[ \t\r\n]*
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment