forked from bonsai/harakit
rpn(1): added From trait to CalcType
This commit is contained in:
parent
0d97f81f49
commit
e7ee75b03f
59
src/rpn.rs
59
src/rpn.rs
@ -50,7 +50,17 @@ use std::{
|
|||||||
process::ExitCode,
|
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;
|
extern crate sysexits;
|
||||||
|
|
||||||
@ -67,6 +77,7 @@ enum CalcType {
|
|||||||
Floor,
|
Floor,
|
||||||
Modulo,
|
Modulo,
|
||||||
Val(f64),
|
Val(f64),
|
||||||
|
Empty,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@ -82,25 +93,23 @@ impl fmt::Display for EvaluationError {
|
|||||||
// repeating and it seems this can give it to me
|
// repeating and it seems this can give it to me
|
||||||
const PRECISION_MOD: f64 = 0.9 + f64::EPSILON * 100.0;
|
const PRECISION_MOD: f64 = 0.9 + f64::EPSILON * 100.0;
|
||||||
|
|
||||||
// str_to_calc_type converts a string to an optional `CalcType`.
|
impl From<&str> for CalcType {
|
||||||
fn str_to_calc_type(string: &str) -> Option<CalcType> {
|
fn from(value: &str) -> Self {
|
||||||
let as_int = string.parse::<f64>();
|
match value {
|
||||||
let result = match as_int {
|
"+" => Add,
|
||||||
Ok(x) => Some(Val(x)),
|
"-" | "−" => Subtract,
|
||||||
Err(_) => None,
|
"*" | "×" => Multiply,
|
||||||
};
|
"/" | "÷" => Divide,
|
||||||
|
"^" => Power,
|
||||||
if result.is_some() { return result; }
|
"//" => Floor,
|
||||||
|
"%" => Modulo,
|
||||||
match string {
|
_ => {
|
||||||
"+" => Some(Add),
|
match value.parse::<f64>() {
|
||||||
"-" | "−" => Some(Subtract),
|
Ok(x) => Val(x),
|
||||||
"*" | "×" => Some(Multiply),
|
Err(_) => Empty,
|
||||||
"/" | "÷" => Some(Divide),
|
}
|
||||||
"^" => Some(Power),
|
},
|
||||||
"//" => Some(Floor),
|
}
|
||||||
"%" => Some(Modulo),
|
|
||||||
_ => None,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -119,14 +128,14 @@ fn eval(
|
|||||||
let toks = input.split(' ').collect::<Vec<&str>>();
|
let toks = input.split(' ').collect::<Vec<&str>>();
|
||||||
let mut ops: VecDeque<CalcType> = VecDeque::new();
|
let mut ops: VecDeque<CalcType> = VecDeque::new();
|
||||||
|
|
||||||
for tok in &toks {
|
for tok in toks {
|
||||||
let x: CalcType = match str_to_calc_type(tok) {
|
let x: CalcType = match CalcType::from(tok) {
|
||||||
Some(x) => x,
|
Empty => {
|
||||||
None => {
|
|
||||||
return Err(EvaluationError {
|
return Err(EvaluationError {
|
||||||
message: format!("Invalid token: {}", tok),
|
message: format!("Invalid token: {}", tok),
|
||||||
})
|
})
|
||||||
}
|
},
|
||||||
|
x => x,
|
||||||
};
|
};
|
||||||
|
|
||||||
match x {
|
match x {
|
||||||
|
Loading…
Reference in New Issue
Block a user