From 61f21c32dbf3d34e419da780b2fd30ce4777629c Mon Sep 17 00:00:00 2001 From: David Senk Date: Thu, 7 Sep 2023 16:25:15 -0400 Subject: [PATCH] intermediate refactor --- src/main.rs | 82 +++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 77 insertions(+), 5 deletions(-) diff --git a/src/main.rs b/src/main.rs index 3e16291..e6085bb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -29,6 +29,9 @@ fn main() { "/" => Function::Divide, "%" => Function::Modulo, "clear" | "c" => Function::ClearStack, + "floor" | "fl" => Function::Floor, + "ceil" | "cl" => Function::Ceil, + "round" | "r" => Function::Round, _ => Function::Push(f64::from_str(input.trim())), }; @@ -47,12 +50,35 @@ fn main() { } } +#[derive(Debug)] enum Function { Add, Subtract, Multiply, Divide, Modulo, + Floor, + Ceil, + Round, + Abs, + Pow, + Sqrt, + Cbrt, + LogN, + Log, + Sin, + Asin, + Sinh, + Acos, + Cos, + Cosh, + Tan, + Atan, + Tanh, + Epsilon, + Euler, + Pi, + Tau, Push(Result), ClearStack, Quit, @@ -65,19 +91,47 @@ fn stack_push(stack: &mut Vec, num: Result) { } } +fn idk_man(func: Function) { + println!("I don't know how to do {func:?}!") +} + +fn small_stack_err(count_expected: i32, func: &str) { + println!("Stack must contain at least {count_expected} numbers to {func}!"); +} + +fn stack_way_too_small_err(func: &str) { + small_stack_err(1, func) +} + fn stack_too_small_err(func: &str) { - println!("Stack must contain at least 2 numbers to {func}!"); + small_stack_err(2, func); +} + +fn operate_single(stack: &mut Vec, func: Function) { + if stack.len() < 1 { + stack_way_too_small_err("anything!!"); + return; + } + + let x = stack.pop().unwrap_or(0f64); + + match func { + Function::Round => stack.push(x.round()), + others => idk_man(others), + } } fn operate(stack: &mut Vec, func: Function) { - if stack.len() < 2 { + if stack.len() <= 1 { match func { Function::Add => stack_too_small_err("add"), Function::Subtract => stack_too_small_err("subtract"), Function::Multiply => stack_too_small_err("multiply"), Function::Divide => stack_too_small_err("divide"), Function::Modulo => stack_too_small_err("modulo"), - _ => {} + Function::Floor => stack_too_small_err("floor"), + Function::Ceil => stack_too_small_err("ceil"), + _ => {} //only above functions require } return; } @@ -93,8 +147,26 @@ fn operate(stack: &mut Vec, func: Function) { //dependent. We're dividing the number input prior //to x (y), by x. i.e. x: 3, y: 6, push = 0.5 Function::Multiply => stack.push(x * y), - Function::Modulo => stack.push(y % x), //same reason as division above - _ => {} //do nothing, as we don't know what to do with it + Function::Modulo => stack.push(y % x), + Function::Floor => stack.push(floor(x, y)), + Function::Ceil => stack.push(ceil(x, y)), + others => idk_man(others), + } +} + +fn floor(a: f64, b: f64) -> f64 { + if a > b { + a + } else { + b + } +} + +fn ceil(a: f64, b: f64) -> f64 { + if a < b { + a + } else { + b } }