Sha256: 34d8368abad64091bc0b4f39a9b005f4adbe1c6dc8719fcc5dd0e0ca6ae19df4
Contents?: true
Size: 819 Bytes
Versions: 4
Compression:
Stored size: 819 Bytes
Contents
require 'parser_combinator/string_parser' class MyParser < ParserCombinator::StringParser parser :expression do add_sub end parser :add_sub do add_op = str("+").map{ proc{|l, r| l + r}} sub_op = str("-").map{ proc{|l, r| l - r}} binopl(mul_div, add_op | sub_op) end parser :mul_div do mul_op = str("*").map{ proc{|l, r| l * r}} div_op = str("/").map{ proc{|l, r| l / r}} binopl(integer | parenth, mul_op | div_op) end parser :integer do many1(digit).map{|x| x.map{|i| i.item}.join.to_i} end parser :parenth do str("(") > expression < str(")") end end result = MyParser.expression.parse_from_string("(1+2)*3+10/2") puts result.parsed # => 14 result = MyParser.expression.parse_from_string("3-2-1") puts result.parsed # => 0
Version data entries
4 entries across 4 versions & 1 rubygems
Version | Path |
---|---|
parser_combinator-0.0.4 | examples/recursive.rb |
parser_combinator-0.0.3 | examples/recursive.rb |
parser_combinator-0.0.2 | examples/recursive.rb |
parser_combinator-0.0.1 | examples/recursive.rb |