rpn(1): added From trait to CalcType

This commit is contained in:
Emma Tebibyte 2024-02-01 23:32:37 -07:00
parent 0d97f81f49
commit e7ee75b03f
Signed by: emma
GPG Key ID: 06FA419A1698C270

View File

@ -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<CalcType> {
let as_int = string.parse::<f64>();
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::<f64>() {
Ok(x) => Val(x),
Err(_) => Empty,
}
},
}
}
}
@ -119,14 +128,14 @@ fn eval(
let toks = input.split(' ').collect::<Vec<&str>>();
let mut ops: VecDeque<CalcType> = 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 {