diff --git a/src/rpn.rs b/src/rpn.rs index 7e7f948..737325c 100644 --- a/src/rpn.rs +++ b/src/rpn.rs @@ -57,7 +57,7 @@ extern crate sysexits; use sysexits::EX_DATAERR; #[derive(Clone, Copy, PartialEq, PartialOrd, Debug)] -/// enum CalcType is a type containing operations used in the calculator. +// enum CalcType is a type containing operations used in the calculator. enum CalcType { Add, Subtract, @@ -78,7 +78,7 @@ impl fmt::Display for EvaluationError { } } -/// str_to_calc_type converts a string to an optional `CalcType`. +// str_to_calc_type converts a string to an optional `CalcType`. fn str_to_calc_type(string: &str) -> Option { let as_int = string.parse::(); let result = match as_int { @@ -105,6 +105,12 @@ fn eval( initial_stack: VecDeque, ) -> Result, EvaluationError> { let mut stack = initial_stack; + + if input.is_empty() { + stack.clear(); + return Ok(stack); + } + // Split the input into tokens. let toks = input.split(' ').collect::>(); let mut ops: VecDeque = VecDeque::new(); @@ -185,12 +191,15 @@ fn main() -> ExitCode { if argv.get(1).is_none() { while let Ok(_) = stdin().read_line(&mut buf) { match eval(&buf.trim(), stack) { - Ok(val) => { - stack = val.clone(); - let precise = round_precise( - stack.iter().last().unwrap(), - precision, - ); + Ok(s) => { + stack = s.clone(); + + let val = match stack.iter().last() { + Some(v) => v, + None => break, + }; + + let precise = round_precise(val, precision); println!("{}", precise.to_string()); buf.clear(); },