RosettaCodeData/Task/Parsing-RPN-calculator-algorithm/Sidef/parsing-rpn-calculator-algorithm.sidef

34 lines
679 B
Text
Raw Permalink Normal View History

2017-09-23 10:01:46 +02:00
var proggie = '3 4 2 * 1 5 - 2 3 ^ ^ / +'
2016-12-05 23:44:36 +01:00
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|
2017-09-23 10:01:46 +02:00
say "#{w} (#{arr})"
2016-12-05 23:44:36 +01:00
given (w) {
when (/\d/) {
2017-09-23 10:01:46 +02:00
arr << Num(w)
2016-12-05 23:44:36 +01:00
}
when (<+ - * />) {
self.binop(w)
}
when ('^') {
self.binop('**')
}
default {
die "#{w} is bogus"
}
}
}
say arr[0]
}
}
2017-09-23 10:01:46 +02:00
RPN.new.run(proggie)