Reverse Polish Notation (RPN) or postfic calculator
// Reverse Polish Notation (RPN) or postfix calculator
fn rpn_evaluator(expr: &str) -> i64 {
let mut stack = vec![];
for text in expr.split(" ") {
match text {
"+" => {
let b = stack.pop().unwrap();
let a = stack.pop().unwrap();
stack.push(a + b);
},
"-" => {
let b = stack.pop().unwrap();
let a = stack.pop().unwrap();
stack.push(a - b);
},
"*" => {
let b = stack.pop().unwrap();
let a = stack.pop().unwrap();
stack.push(a * b);
},
"/" => {
let b = stack.pop().unwrap();
let a = stack.pop().unwrap();
stack.push(a / b);
},
num => {
stack.push(num.parse().unwrap());
}
}
}
stack.pop().unwrap()
}
fn main() {
println!("RPN evaluator = {} ", rpn_evaluator("45 35 +")); // 80
println!("RPN evaluator = {} ", rpn_evaluator("4 8 + 6 5 - * 3 2 - 2 2 + * /")); // 3
}