Sha256: ab7f5471a03ee3da7aad1ab0bcdca0bccf14d6cd91a10f051f326b8fc5711512

Contents?: true

Size: 1017 Bytes

Versions: 18

Compression:

Stored size: 1017 Bytes

Contents

# $Id$
#
# Very simple calculater.

class Calcp
  prechigh
    nonassoc UMINUS
    left '*' '/'
    left '+' '-'
  preclow
rule
  target: exp
        | /* none */ { result = 0 }

  exp: exp '+' exp { result += val[2] }
     | exp '-' exp { result -= val[2] }
     | exp '*' exp { result *= val[2] }
     | exp '/' exp { result /= val[2] }
     | '(' exp ')' { result = val[1] }
     | '-' NUMBER  =UMINUS { result = -val[1] }
     | NUMBER
end

---- header
# $Id$
---- inner
  
  def parse(str)
    @q = []
    until str.empty?
      case str
      when /\A\s+/
      when /\A\d+/
        @q.push [:NUMBER, $&.to_i]
      when /\A.|\n/o
        s = $&
        @q.push [s, s]
      end
      str = $'
    end
    @q.push [false, '$end']
    do_parse
  end

  def next_token
    @q.shift
  end

---- footer

parser = Calcp.new
puts
puts 'type "Q" to quit.'
puts
while true
  puts
  print '? '
  str = gets.chop!
  break if /q/i =~ str
  begin
    puts "= #{parser.parse(str)}"
  rescue ParseError
    puts $!
  end
end

Version data entries

18 entries across 18 versions & 2 rubygems

Version Path
racc-1.4.16-java sample/calc.y
racc-1.4.16 sample/calc.y
racc-1.4.15-java sample/calc.y
racc-1.4.15 sample/calc.y
racc-1.4.14-java sample/calc.y
racc-1.4.14 sample/calc.y
racc-1.4.13-java sample/calc.y
racc-1.4.13 sample/calc.y
racc-1.4.12-java sample/calc.y
racc-1.4.12 sample/calc.y
racc-1.4.11 sample/calc.y
gd-racc-1.4.11 sample/calc.y
racc-1.4.10 sample/calc.y
racc-1.4.9-java sample/calc.y
racc-1.4.9 sample/calc.y
racc-1.4.8 sample/calc.y
racc-1.4.7 sample/calc.y
racc-1.4.6 sample/calc.y