File: arithmetic.rb

package info (click to toggle)
ruby-rsec 0.4.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 272 kB
  • sloc: ruby: 2,130; lisp: 13; makefile: 3
file content (28 lines) | stat: -rw-r--r-- 645 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# arithmetic parser

require "rsec"

include Rsec::Helpers

def arithmetic
  calculate = proc do |(p, *ps)|
    ps.each_slice(2).inject(p) do |left, (op, right)|
      left.send op, right
    end
  end

  num    = prim(:double).fail 'number'
  paren  = '('.r >> lazy{expr} << ')'
  factor = num | paren
  term   = factor.join(one_of_('*/%').fail 'operator').map &calculate
  expr   = term.join(one_of_('+-').fail 'operator').map &calculate
  expr.eof
end

if __FILE__ == $PROGRAM_NAME
  print '1+ 2*4 = '
  p arithmetic.parse! '1+ 2*4' #=> 9
  print '1+ 2*/4 = '
  p arithmetic.parse! '1+ 2*/4' #=> syntax error
end