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> {
let mut stack: Vec<i32> = Vec::new();
let last_result = inputs.iter().fold(None, |_, entry| match entry {
CalculatorInput::Value(x) => {
stack.push(*x);
Some(*x)
}
CalculatorInput::Add => {
let val1 = stack.pop()?;
let val2 = stack.pop()?;
let result = val2 + val1;
stack.push(result);
Some(result)
let last_result = inputs.iter().fold(None, |current: Option<i32>, entry| {
match (entry, stack.pop()) {
(CalculatorInput::Value(x), None) => {
stack.push(current.unwrap());
if let Some(y) = current {
stack.push(y);
}
CalculatorInput::Subtract => {
let val1 = stack.pop()?;
let val2 = stack.pop()?;
let result = val2 - val1;
stack.push(result);
Some(result)
Some(*x)
}
CalculatorInput::Multiply => {
let val1 = stack.pop()?;
let val2 = stack.pop()?;
let result = val2 * val1;
stack.push(result);
Some(result)
(CalculatorInput::Value(x), Some(y)) => {
stack.push(y);
stack.push(current.unwrap());
Some(*x)
}
CalculatorInput::Divide => {
let val1 = stack.pop()?;
let val2 = stack.pop()?;
let result = val2 / val1;
stack.push(result);
Some(result)
(CalculatorInput::Add, Some(x)) => Some(current.unwrap() + x),
(CalculatorInput::Subtract, Some(x)) => Some(x - current.unwrap()),
(CalculatorInput::Multiply, Some(x)) => Some(x * current.unwrap()),
(CalculatorInput::Divide, Some(x)) => Some(x / current.unwrap()),
_ => None,
}
});
if stack.len() == 1 {
if stack.is_empty() {
last_result
} else {
// too many operands

Loading…
Cancel
Save