From e7ee75b03fb560083587fb484648a3cef4650bb9 Mon Sep 17 00:00:00 2001 From: emma Date: Thu, 1 Feb 2024 23:32:37 -0700 Subject: [PATCH] rpn(1): added From trait to CalcType --- src/rpn.rs | 59 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 34 insertions(+), 25 deletions(-) diff --git a/src/rpn.rs b/src/rpn.rs index 16ba94f..88c04ba 100644 --- a/src/rpn.rs +++ b/src/rpn.rs @@ -50,7 +50,17 @@ use std::{ process::ExitCode, }; -use CalcType::{ Add, Divide, Floor, Modulo, Multiply, Power, Subtract, Val }; +use CalcType::{ + Add, + Divide, + Empty, + Floor, + Modulo, + Multiply, + Power, + Subtract, + Val +}; extern crate sysexits; @@ -67,6 +77,7 @@ enum CalcType { Floor, Modulo, Val(f64), + Empty, } #[derive(Debug, Clone)] @@ -82,25 +93,23 @@ impl fmt::Display for EvaluationError { // repeating and it seems this can give it to me const PRECISION_MOD: f64 = 0.9 + f64::EPSILON * 100.0; -// 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 { - Ok(x) => Some(Val(x)), - Err(_) => None, - }; - - if result.is_some() { return result; } - - match string { - "+" => Some(Add), - "-" | "−" => Some(Subtract), - "*" | "×" => Some(Multiply), - "/" | "÷" => Some(Divide), - "^" => Some(Power), - "//" => Some(Floor), - "%" => Some(Modulo), - _ => None, +impl From<&str> for CalcType { + fn from(value: &str) -> Self { + match value { + "+" => Add, + "-" | "−" => Subtract, + "*" | "×" => Multiply, + "/" | "÷" => Divide, + "^" => Power, + "//" => Floor, + "%" => Modulo, + _ => { + match value.parse::() { + Ok(x) => Val(x), + Err(_) => Empty, + } + }, + } } } @@ -119,14 +128,14 @@ fn eval( let toks = input.split(' ').collect::>(); let mut ops: VecDeque = VecDeque::new(); - for tok in &toks { - let x: CalcType = match str_to_calc_type(tok) { - Some(x) => x, - None => { + for tok in toks { + let x: CalcType = match CalcType::from(tok) { + Empty => { return Err(EvaluationError { message: format!("Invalid token: {}", tok), }) - } + }, + x => x, }; match x {