From 731e62ee7ea81e0aa5b9cdb34a233e83b69ae0e4 Mon Sep 17 00:00:00 2001 From: emma Date: Wed, 28 Aug 2024 18:24:49 -0600 Subject: [PATCH] rpn(1): made evaluation function more readable --- src/rpn.rs | 49 +++++++++++++++++++++++++++++-------------------- 1 file changed, 29 insertions(+), 20 deletions(-) diff --git a/src/rpn.rs b/src/rpn.rs index d1cd3c3..6907772 100644 --- a/src/rpn.rs +++ b/src/rpn.rs @@ -138,6 +138,33 @@ fn err(argv0: &String, e: &T, code: Option) -> ExitCode { ExitCode::from(code.unwrap_or(1 /* unknown error */)) } +fn operate( + mut stack: VecDeque, + op: CalcType, +) -> Result, EvaluationError> { + let vals = (stack.pop_back(), stack.pop_back()); + + if let (Some(x), Some(y)) = vals { + match op { + Add => stack.push_back(y + x), + Subtract => stack.push_back(y - x), + Multiply => stack.push_back(y * x), + Divide => stack.push_back(y / x), + Power => stack.push_back(y.powf(x)), + Floor => stack.push_back((y / x).floor()), + Modulo => stack.push_back(y % x), + _ => {}, + }; + } else { + return Err(EvaluationError { + message: format!("{}: unexpected operation", op), + code: EX_DATAERR, + }) + } + + Ok(stack) +} + fn eval( input: &str, initial_stack: VecDeque, @@ -170,27 +197,9 @@ fn eval( }, op => { ops.push_back(op.clone()); + oper = true; /* this is an operation */ - - let vals = (stack.pop_back(), stack.pop_back()); - - if let (Some(x), Some(y)) = vals { - match op { - Add => stack.push_back(y + x), - Subtract => stack.push_back(y - x), - Multiply => stack.push_back(y * x), - Divide => stack.push_back(y / x), - Power => stack.push_back(y.powf(x)), - Floor => stack.push_back((y / x).floor()), - Modulo => stack.push_back(y % x), - _ => {}, - }; - } else { - return Err(EvaluationError { - message: format!("{}: unexpected operation", op), - code: EX_DATAERR, - }) - } + return operate(stack, op).map(|s| (s, oper)); }, }; }