演算子を前に置くのをポーランド記法という 4 + 5 * 8 – 9 / 3 は、「- + 4 * 5 8 / 9 3」っと書く。
逆に、演算子を後ろに置くのを逆ポーランド記法という。「4 5 8 * + 9 3 / -」と書く。
逆ポーランド記法はスタックで処理しやすく、色々な場面で使われる。
fn calc(expression: String) {
let mut stack: Vec<i32> = Vec::new();
for i in expression.split(' ') {
println!("{:?}", stack);
if i == '+'.to_string() {
let b = stack.pop().unwrap();
let a = stack.pop().unwrap();
stack.push(a + b);
} else if i == '-'.to_string() {
let b = stack.pop().unwrap();
let a = stack.pop().unwrap();
stack.push(a - b);
} else if i == '*'.to_string() {
let b = stack.pop().unwrap();
let a = stack.pop().unwrap();
stack.push(a * b);
} else if i == '/'.to_string() {
let b = stack.pop().unwrap();
let a = stack.pop().unwrap();
stack.push(a / b);
} else {
stack.push(i.parse::<i32>().unwrap());
}
}
println!("{:?}", stack);
}
fn main() {
calc("4 6 2 + * 3 1 - 5 * -".to_string());
}
[]
[4]
[4, 6]
[4, 6, 2]
[4, 8]
[32]
[32, 3]
[32, 3, 1]
[32, 2]
[32, 2, 5]
[32, 10]
[22]
なるほど、これは面白い。
コンパイラのOP_CODEでも同じようなことをやったような気がする。