adition: All basic operations

This commit is contained in:
2026-04-27 17:27:05 -06:00
parent 44cc35ce49
commit 9e28ac0b39

View File

@@ -30,7 +30,11 @@ impl Fraction {
return Err(FractionError::ZeroDenominator); return Err(FractionError::ZeroDenominator);
} }
Ok(Fraction { num, den }) let mut new = Fraction { num, den };
new.reduce();
Ok(new)
} }
pub fn reciprocal(&self) -> Result<Self, FractionError> { pub fn reciprocal(&self) -> Result<Self, FractionError> {
@@ -56,37 +60,68 @@ impl Fraction {
fn reduce(&mut self) { fn reduce(&mut self) {
todo!(); todo!();
} }
fn correct_sign(&mut self) {
todo!()
}
} }
impl ops::Mul for Fraction { impl ops::Mul for Fraction {
type Output = Self; type Output = Self;
fn mul(self, rhs: Self) -> Self::Output { fn mul(self, other: Self) -> Self::Output {
todo!() let mut new = Fraction {
num: self.num * other.num,
den: self.den * other.den,
};
new.reduce();
new
} }
} }
impl ops::Add for Fraction { impl ops::Add for Fraction {
type Output = Self; type Output = Self;
fn add(self, rhs: Self) -> Self::Output { fn add(self, other: Self) -> Self::Output {
todo!() 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 { impl ops::Div for Fraction {
type Output = Result<Self, FractionError>; type Output = Result<Self, FractionError>;
fn div(self, rhs: Self) -> Self::Output { fn div(self, other: Self) -> Self::Output {
todo!() 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 { impl ops::Sub for Fraction {
type Output = Self; type Output = Self;
fn sub(self, rhs: Self) -> Self::Output { fn sub(self, other: Self) -> Self::Output {
todo!() 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; type Output = Self;
fn neg(self) -> Self::Output { fn neg(self) -> Self::Output {
todo!() Fraction {
num: -self.num,
den: self.den,
}
} }
} }