Browse Source

I love match

master
Julio Biason 3 years ago
parent
commit
eee503f4e2
  1. 47
      rust/rpn-calculator/src/lib.rs

47
rust/rpn-calculator/src/lib.rs

@ -9,42 +9,29 @@ pub enum CalculatorInput {
pub fn evaluate(inputs: &[CalculatorInput]) -> Option<i32> { pub fn evaluate(inputs: &[CalculatorInput]) -> Option<i32> {
let mut stack: Vec<i32> = Vec::new(); let mut stack: Vec<i32> = Vec::new();
let last_result = inputs.iter().fold(None, |_, entry| match entry { let last_result = inputs.iter().fold(None, |current: Option<i32>, entry| {
CalculatorInput::Value(x) => { match (entry, stack.pop()) {
stack.push(*x); (CalculatorInput::Value(x), None) => {
Some(*x) stack.push(current.unwrap());
} if let Some(y) = current {
CalculatorInput::Add => { stack.push(y);
let val1 = stack.pop()?;
let val2 = stack.pop()?;
let result = val2 + val1;
stack.push(result);
Some(result)
} }
CalculatorInput::Subtract => { Some(*x)
let val1 = stack.pop()?;
let val2 = stack.pop()?;
let result = val2 - val1;
stack.push(result);
Some(result)
} }
CalculatorInput::Multiply => { (CalculatorInput::Value(x), Some(y)) => {
let val1 = stack.pop()?; stack.push(y);
let val2 = stack.pop()?; stack.push(current.unwrap());
let result = val2 * val1; Some(*x)
stack.push(result);
Some(result)
} }
CalculatorInput::Divide => { (CalculatorInput::Add, Some(x)) => Some(current.unwrap() + x),
let val1 = stack.pop()?; (CalculatorInput::Subtract, Some(x)) => Some(x - current.unwrap()),
let val2 = stack.pop()?; (CalculatorInput::Multiply, Some(x)) => Some(x * current.unwrap()),
let result = val2 / val1; (CalculatorInput::Divide, Some(x)) => Some(x / current.unwrap()),
stack.push(result); _ => None,
Some(result)
} }
}); });
if stack.len() == 1 { if stack.is_empty() {
last_result last_result
} else { } else {
// too many operands // too many operands

Loading…
Cancel
Save