From eba531741920955aa842f70a504359ff6387e1eb Mon Sep 17 00:00:00 2001 From: Valerie Date: Wed, 9 Oct 2024 15:22:47 -0400 Subject: [PATCH] added a rudimentary fraction representation helper --- src/context/helper.rs | 20 ++++++++++++++++++++ src/context/mod.rs | 1 + src/main.rs | 1 - 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/context/helper.rs b/src/context/helper.rs index 664fed8..8e7a9a5 100644 --- a/src/context/helper.rs +++ b/src/context/helper.rs @@ -1,3 +1,4 @@ + use evalexpr::{ Value, @@ -38,6 +39,25 @@ pub fn fix(arg: &Value) -> EvalResult { } else { Err(EvalexprError::wrong_function_argument_amount(1, 2)) } } +pub fn fraction(arg: &Value) -> EvalResult { + if let Value::Float(arg) = arg { + let mut intermediate = arg.clone(); + let mut pow = 0; + while intermediate.fract() != 0_f64 { + intermediate *= 10_f64; + pow += 1; + } + let value = intermediate as i64; + let tens: i64 = 10_i64.pow(pow); + let gcd = util::gcd(value, tens); + + let numerator = value / gcd; + let denominator = tens / gcd; + + Ok(Value::String(format!("{numerator}/{denominator}"))) + } else { Err(EvalexprError::expected_float(arg.clone())) } +} + pub fn greatest_common_divisor(arg: &Value) -> EvalResult { if let Value::Tuple(args) = arg { let len = args.len(); diff --git a/src/context/mod.rs b/src/context/mod.rs index 58ccdd1..e6beeb6 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -27,6 +27,7 @@ pub fn build(args: &mut Arguments) -> HashMapContext { // math functions "cos" => Function::new(|arg| helper::cosine(arg)), + "fract" => Function::new(|arg| helper::fraction(arg)), "fix" => Function::new(|arg| helper::fix(arg)), "gcd" => Function::new(|arg| helper::greatest_common_divisor(arg)), "lcm" => Function::new(|arg| helper::least_common_multiple(arg)), diff --git a/src/main.rs b/src/main.rs index 6a68dd6..ce17174 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,7 +14,6 @@ use std::{ use evalexpr::{ eval_with_context_mut, - ContextWithMutableVariables, EvalexprError, HashMapContext, Value