adition: All basic operations
This commit is contained in:
58
src/lib.rs
58
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<Self, FractionError> {
|
||||
@@ -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<Self, FractionError>;
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user