From 09eb85fda469c1467662d7c9ae381a0b943c1a07 Mon Sep 17 00:00:00 2001 From: David Senk Date: Thu, 7 Sep 2023 14:56:38 -0400 Subject: [PATCH] basic functionality --- src/main.rs | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 69 insertions(+), 3 deletions(-) diff --git a/src/main.rs b/src/main.rs index 6e43406..c0cdd89 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,11 +1,15 @@ use std::io; use std::io::Write; +use std::str::FromStr; fn main() { - println!("Hello, world!"); + println!("RPN Calculator"); + + let mut stack: Vec = Vec::new(); loop { let mut input = String::new(); + print!("> "); io::stdout() @@ -16,8 +20,70 @@ fn main() { .read_line(&mut input) .expect("failed to read line"); - let output = input.trim(); + let func = match input.trim() { + "q" => Function::Quit, + "+" => Function::Add, + "-" => Function::Subtract, + "*" | "x" => Function::Multiply, + "/" => Function::Divide, + "%" => Function::Modulo, + _ => Function::Push(f64::from_str(input.trim()).expect("valid number")), + }; - println!("input received: '{output}'"); + match func { + Function::Push(x) => stack.push(x), + Function::Quit => break, + others => operate(&mut stack, others), + } + + println!("Current Stack: "); + + for i in &stack { + println!("{i}"); + } + } +} + +enum Function { + Add, + Subtract, + Multiply, + Divide, + Modulo, + Push(f64), + Quit, +} + +fn stack_too_small_err(func: &str) { + println!("Stack must contain at least 2 numbers to {func}!"); +} + +fn operate(stack: &mut Vec, func: Function) { + if stack.len() < 2 { + 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"), + _ => {} + } + return; + } + + let x = stack.pop().unwrap_or(0f64); + let y = stack.pop().unwrap_or(0f64); + + match func { + Function::Add => stack.push(x + y), + Function::Subtract => stack.push(x - y), + Function::Divide => stack.push(y / x), + //x is at top of stack, but divide is order + //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 } }