From 5f8e90b592719a28b558c9d5b5c3aa8c5154d3e0 Mon Sep 17 00:00:00 2001 From: emma Date: Thu, 1 Feb 2024 01:26:48 -0700 Subject: [PATCH] rpn(1): added modulo --- src/rpn.rs | 33 +++++++++++++-------------------- 1 file changed, 13 insertions(+), 20 deletions(-) diff --git a/src/rpn.rs b/src/rpn.rs index 83af537..893266f 100644 --- a/src/rpn.rs +++ b/src/rpn.rs @@ -50,7 +50,7 @@ use std::{ process::ExitCode, }; -use CalcType::{ Add, Divide, Multiply, Power, Subtract, Val }; +use CalcType::{ Add, Divide, Modulo, Multiply, Power, Subtract, Val }; extern crate sysexits; @@ -64,6 +64,7 @@ enum CalcType { Multiply, Divide, Power, + Modulo, Val(f64), } @@ -100,6 +101,7 @@ fn str_to_calc_type(string: &str) -> Option { "*" => Some(Multiply), "/" => Some(Divide), "^" => Some(Power), + "%" => Some(Modulo), _ => None, } } @@ -130,15 +132,16 @@ fn eval( }; 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_), } } for op in &ops { match op { - Add | Subtract | Multiply | Divide | Power => { + Add | Subtract | Multiply | Divide | Power | Modulo => { let x = &stack.pop_back().ok_or(EvaluationError { message: "Stack is empty.".to_string(), })?; @@ -148,22 +151,12 @@ fn eval( })?; match op { - Add => { - &stack.push_back(y + x) - }, - Subtract => { - &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) - }, + Add => &stack.push_back(y + x), + Subtract => &stack.push_back(y - x), + Multiply => &stack.push_back(y * x), + Divide => &stack.push_back(y / x), + Power => &stack.push_back(x.powf(*y)), + Modulo => &stack.push_back(y % x), _ => &{}, }; },