Skip to content

Instantly share code, notes, and snippets.

@courtneyfaulkner
Created September 6, 2017 04:22
Show Gist options
  • Save courtneyfaulkner/c41defa8166bedd3f50a96292f5fc279 to your computer and use it in GitHub Desktop.
Save courtneyfaulkner/c41defa8166bedd3f50a96292f5fc279 to your computer and use it in GitHub Desktop.
[RPNCalculator] #practice
import java.util.*;
class RpnCalculator {
static void main(String[] args) {
Calculator calc = new Calculator()
'4 6 3 + 9 3 - * 1 1 ^ - +'.split(' ').each {calc.enter(it)}
}
}
class Calculator {
Stack stack = [] as Stack
def calculate = {action-> return { action.call(stack.pop(), stack.pop()) }}
def actions = [
'+': calculate {a,b -> b + a},
'-': calculate {a,b -> b - a},
'*': calculate {a,b -> b * a},
'/': calculate {a,b -> b / a},
'^': calculate {a,b -> b ** a}
]
void enter(String entry) {
def action = actions[entry]
BigDecimal last = null
if (action) {
if (stack.size() > 1) {
last = action.call()
stack.push(last)
} else if (stack.size() == 1) {
last = stack.peek()
}
} else if (entry.isBigDecimal()) {
stack.push(entry as BigDecimal)
last = entry as BigDecimal
}
if (last != null) {
println "$stack: $last"
} else {
println stack
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment