@@ -421,25 +421,68 @@ mul_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
421
421
///
422
422
/// # Examples
423
423
///
424
- /// A trivial implementation of `Div`. When `Foo / Foo` happens, it ends up
425
- /// calling `div`, and therefore, `main` prints `Dividing!`.
424
+ /// Implementing a `Div`idable rational number struct:
426
425
///
427
426
/// ```
428
427
/// use std::ops::Div;
429
428
///
430
- /// struct Foo;
429
+ /// // The uniqueness of rational numbers in lowest terms is a consequence of
430
+ /// // the fundamental theorem of arithmetic.
431
+ /// #[derive(Eq)]
432
+ /// #[derive(PartialEq, Debug)]
433
+ /// struct Rational {
434
+ /// nominator: usize,
435
+ /// denominator: usize,
436
+ /// }
431
437
///
432
- /// impl Div for Foo {
433
- /// type Output = Foo;
438
+ /// impl Rational {
439
+ /// fn new(nominator: usize, denominator: usize) -> Self {
440
+ /// if denominator == 0 {
441
+ /// panic!("Zero is an invalid denominator!");
442
+ /// }
434
443
///
435
- /// fn div(self, _rhs: Foo) -> Foo {
436
- /// println!("Dividing!");
437
- /// self
444
+ /// // Reduce to lowest terms by dividing by the greatest common
445
+ /// // divisor.
446
+ /// let gcd = gcd(nominator, denominator);
447
+ /// Rational {
448
+ /// nominator: nominator / gcd,
449
+ /// denominator: denominator / gcd,
450
+ /// }
451
+ /// }
452
+ /// }
453
+ ///
454
+ /// impl Div for Rational {
455
+ /// // The division of rational numbers is a closed operation.
456
+ /// type Output = Self;
457
+ ///
458
+ /// fn div(self, rhs: Self) -> Self {
459
+ /// if rhs.nominator == 0 {
460
+ /// panic!("Cannot divide by zero-valued `Rational`!");
461
+ /// }
462
+ ///
463
+ /// let nominator = self.nominator * rhs.denominator;
464
+ /// let denominator = self.denominator * rhs.nominator;
465
+ /// Rational::new(nominator, denominator)
466
+ /// }
467
+ /// }
468
+ ///
469
+ /// // Euclid's two-thousand-year-old algorithm for finding the greatest common
470
+ /// // divisor.
471
+ /// fn gcd(x: usize, y: usize) -> usize {
472
+ /// let mut x = x;
473
+ /// let mut y = y;
474
+ /// while y != 0 {
475
+ /// let t = y;
476
+ /// y = x % y;
477
+ /// x = t;
438
478
/// }
479
+ /// x
439
480
/// }
440
481
///
441
482
/// fn main() {
442
- /// Foo / Foo;
483
+ /// assert_eq!(Rational::new(1, 2), Rational::new(2, 4));
484
+ /// assert_eq!(Rational::new(1, 2) / Rational::new(3, 4),
485
+ /// Rational::new(2, 3));
443
486
/// }
444
487
/// ```
445
488
///
0 commit comments