1
0
forked from bonsai/harakit

rpn(1): added modulo

This commit is contained in:
Emma Tebibyte 2024-02-01 01:26:48 -07:00
parent 5debb9d954
commit 5f8e90b592
Signed by untrusted user: emma
GPG Key ID: 06FA419A1698C270

View File

@ -50,7 +50,7 @@ use std::{
process::ExitCode, process::ExitCode,
}; };
use CalcType::{ Add, Divide, Multiply, Power, Subtract, Val }; use CalcType::{ Add, Divide, Modulo, Multiply, Power, Subtract, Val };
extern crate sysexits; extern crate sysexits;
@ -64,6 +64,7 @@ enum CalcType {
Multiply, Multiply,
Divide, Divide,
Power, Power,
Modulo,
Val(f64), Val(f64),
} }
@ -100,6 +101,7 @@ fn str_to_calc_type(string: &str) -> Option<CalcType> {
"*" => Some(Multiply), "*" => Some(Multiply),
"/" => Some(Divide), "/" => Some(Divide),
"^" => Some(Power), "^" => Some(Power),
"%" => Some(Modulo),
_ => None, _ => None,
} }
} }
@ -130,15 +132,16 @@ fn eval(
}; };
match x { match x {
Add | Divide | Multiply | Power | Subtract => ops.push_back(x), Add | Divide | Multiply | Power | Subtract | Modulo => {
ops.push_back(x)
},
Val(x_) => stack.push_back(x_), Val(x_) => stack.push_back(x_),
} }
} }
for op in &ops { for op in &ops {
match op { match op {
Add | Subtract | Multiply | Divide | Power => { Add | Subtract | Multiply | Divide | Power | Modulo => {
let x = &stack.pop_back().ok_or(EvaluationError { let x = &stack.pop_back().ok_or(EvaluationError {
message: "Stack is empty.".to_string(), message: "Stack is empty.".to_string(),
})?; })?;
@ -148,22 +151,12 @@ fn eval(
})?; })?;
match op { match op {
Add => { Add => &stack.push_back(y + x),
&stack.push_back(y + x) Subtract => &stack.push_back(y - x),
}, Multiply => &stack.push_back(y * x),
Subtract => { Divide => &stack.push_back(y / x),
&stack.push_back(y - x) Power => &stack.push_back(x.powf(*y)),
}, Modulo => &stack.push_back(y % x),
Multiply => {
&stack.push_back(y * x)
},
Divide => {
&stack.push_back(y / x)
},
Power => {
let result = x.powf(*y);
&stack.push_back(result)
},
_ => &{}, _ => &{},
}; };
}, },