addition: Fraction Error, Fraction and constructor

This commit is contained in:
2026-04-27 16:48:37 -06:00
parent 3e88e6f5c3
commit 95a38620c1

View File

@@ -1,14 +1,38 @@
pub fn add(left: u64, right: u64) -> u64 {
left + right
pub struct Fraction {
num: i64,
den: i64,
}
#[derive(Debug)]
pub enum FractionError {
DivisionByZero,
ZeroDenominator,
Overflow,
}
impl std::fmt::Display for FractionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FractionError::DivisionByZero => write!(f, "Division by zero"),
FractionError::ZeroDenominator => write!(f, "Denominator can't be zero"),
FractionError::Overflow => write!(f, "Numeric overflow"),
}
}
}
impl std::error::Error for FractionError {}
impl Fraction {
pub fn new(num: i64, den: i64) -> Result<Self, FractionError> {
if den == 0 {
return Err(FractionError::ZeroDenominator);
}
Ok(Fraction { num, den })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
}