RPN calculator algorithm

var proggie = '3 4 2 * 1 5 - 2 3 ^ ^ / +'

class RPN(arr=[]) {

    method binop(op) {
        var x = arr.pop
        var y = arr.pop
        arr << y.(op)(x)
    }

    method run(p) {
        p.each_word { |w|
            say "#{w} (#{arr})"
            given (w) {
                when (/\d/) {
                    arr << Num(w)
                }
                when (<+ - * />) {
                    self.binop(w)
                }
                when ('^') {
                    self.binop('**')
                }
                default {
                    die "#{w} is bogus"
                }
            }
        }
        say arr[0]
    }
}

RPN.new.run(proggie)

Output:

Last updated

Was this helpful?