@@ -274,26 +274,63 @@ sub_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
274
274
///
275
275
/// # Examples
276
276
///
277
- /// A trivial implementation of `Mul`. When `Foo * Foo` happens, it ends up
278
- /// calling `mul`, and therefore, `main` prints `Multiplying!`.
277
+ /// Implementing a `Mul`tipliable rational number struct:
279
278
///
280
279
/// ```
281
280
/// use std::ops::Mul;
282
281
///
283
- /// struct Foo;
282
+ /// // The uniqueness of rational numbers in lowest terms is a consequence of
283
+ /// // the fundamental theorem of arithmetic.
284
+ /// #[derive(Eq)]
285
+ /// #[derive(PartialEq, Debug)]
286
+ /// struct Rational {
287
+ /// nominator: usize,
288
+ /// denominator: usize,
289
+ /// }
290
+ ///
291
+ /// impl Rational {
292
+ /// fn new(nominator: usize, denominator: usize) -> Self {
293
+ /// if denominator == 0 {
294
+ /// panic!("Zero is an invalid denominator!");
295
+ /// }
296
+ ///
297
+ /// // Reduce to lowest terms by dividing by the greatest common
298
+ /// // divisor.
299
+ /// let gcd = gcd(nominator, denominator);
300
+ /// Rational {
301
+ /// nominator: nominator / gcd,
302
+ /// denominator: denominator / gcd,
303
+ /// }
304
+ /// }
305
+ /// }
284
306
///
285
- /// impl Mul for Foo {
286
- /// type Output = Foo;
307
+ /// impl Mul for Rational {
308
+ /// // The multiplication of rational numbers is a closed operation.
309
+ /// type Output = Self;
287
310
///
288
- /// fn mul(self, _rhs: Foo) -> Foo {
289
- /// println!("Multiplying!");
290
- /// self
311
+ /// fn mul(self, rhs: Self) -> Self {
312
+ /// let nominator = self.nominator * rhs.nominator;
313
+ /// let denominator = self.denominator * rhs.denominator;
314
+ /// Rational::new(nominator, denominator)
291
315
/// }
292
316
/// }
293
317
///
294
- /// fn main() {
295
- /// Foo * Foo;
318
+ /// // Euclid's two-thousand-year-old algorithm for finding the greatest common
319
+ /// // divisor.
320
+ /// fn gcd(x: usize, y: usize) -> usize {
321
+ /// let mut x = x;
322
+ /// let mut y = y;
323
+ /// while y != 0 {
324
+ /// let t = y;
325
+ /// y = x % y;
326
+ /// x = t;
327
+ /// }
328
+ /// x
296
329
/// }
330
+ ///
331
+ /// assert_eq!(Rational::new(1, 2), Rational::new(2, 4));
332
+ /// assert_eq!(Rational::new(2, 3) * Rational::new(3, 4),
333
+ /// Rational::new(1, 2));
297
334
/// ```
298
335
#[ lang = "mul" ]
299
336
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
0 commit comments