-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
29 lines (27 loc) · 892 Bytes
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#[derive(Debug)]
pub enum CalculatorInput {
Add,
Subtract,
Multiply,
Divide,
Value(i32),
}
pub fn evaluate(inputs: &[CalculatorInput]) -> Option<i32> {
let mut eval_stack: Vec<i32> = Vec::new();
for op in inputs.iter() {
match op {
CalculatorInput::Value(val) => eval_stack.push(*val),
op => {
let (l, r) = (eval_stack.pop()?, eval_stack.pop()?);
match op {
CalculatorInput::Add => eval_stack.push(l + r),
CalculatorInput::Subtract => eval_stack.push(r - l),
CalculatorInput::Multiply => eval_stack.push(l * r),
CalculatorInput::Divide => eval_stack.push(r / l),
_ => unreachable!(),
}
}
}
}
(eval_stack.len() == 1).then(|| eval_stack.pop()).flatten()
}