From 9e28ac0b39ec9b564301f9872e8948a8558b7204 Mon Sep 17 00:00:00 2001 From: laentropia Date: Mon, 27 Apr 2026 17:27:05 -0600 Subject: [PATCH] adition: All basic operations --- src/lib.rs | 58 ++++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 48 insertions(+), 10 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 7a44ec0..140eba1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -30,7 +30,11 @@ impl Fraction { return Err(FractionError::ZeroDenominator); } - Ok(Fraction { num, den }) + let mut new = Fraction { num, den }; + + new.reduce(); + + Ok(new) } pub fn reciprocal(&self) -> Result { @@ -56,37 +60,68 @@ impl Fraction { fn reduce(&mut self) { todo!(); } + + fn correct_sign(&mut self) { + todo!() + } } impl ops::Mul for Fraction { type Output = Self; - fn mul(self, rhs: Self) -> Self::Output { - todo!() + fn mul(self, other: Self) -> Self::Output { + let mut new = Fraction { + num: self.num * other.num, + den: self.den * other.den, + }; + new.reduce(); + new } } impl ops::Add for Fraction { type Output = Self; - fn add(self, rhs: Self) -> Self::Output { - todo!() + fn add(self, other: Self) -> Self::Output { + let mut new = Fraction { + num: (self.num * other.den) + (self.den * other.num), + den: self.num * other.den, + }; + new.reduce(); + new.correct_sign(); + new } } impl ops::Div for Fraction { type Output = Result; - fn div(self, rhs: Self) -> Self::Output { - todo!() + fn div(self, other: Self) -> Self::Output { + if other.is_zero() { + return Err(FractionError::DivisionByZero); + } + + let mut new = Fraction { + num: self.num * other.den, + den: self.den * other.num, + }; + new.reduce(); + new.correct_sign(); + Ok(new) } } impl ops::Sub for Fraction { type Output = Self; - fn sub(self, rhs: Self) -> Self::Output { - todo!() + fn sub(self, other: Self) -> Self::Output { + let mut new = Fraction { + num: (self.num * other.den) - (self.den * other.num), + den: self.num * other.den, + }; + new.reduce(); + new.correct_sign(); + new } } @@ -94,7 +129,10 @@ impl ops::Neg for Fraction { type Output = Self; fn neg(self) -> Self::Output { - todo!() + Fraction { + num: -self.num, + den: self.den, + } } }