Created
September 24, 2013 05:35
-
-
Save shelling/6680747 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| #!/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 |
This file contains hidden or 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
| 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