From 34b9a80e7707637de2965f9e113be71010ab75ce Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Fri, 15 Mar 2019 14:28:21 -0400 Subject: [PATCH] Slightly improve fibonacci and factorial examples --- __non-book-expirements__/factorial/src/main.rs | 18 +++++++----------- __non-book-expirements__/fibonacci/src/main.rs | 10 ++++------ 2 files changed, 11 insertions(+), 17 deletions(-) diff --git a/__non-book-expirements__/factorial/src/main.rs b/__non-book-expirements__/factorial/src/main.rs index 0b84929..900845a 100644 --- a/__non-book-expirements__/factorial/src/main.rs +++ b/__non-book-expirements__/factorial/src/main.rs @@ -12,18 +12,14 @@ use std::u128; /// If the result overflows, an error message will be displayed. fn factorial (n: usize, table: &mut Vec) -> Option { match table.get(n) { - Some(x) => { - // Vec.get returns a Option with a reference to the value, so deref - // Wrap in Some() for proper return type - Some(*x) - }, + // Vec.get returns a Option with a reference to the value, + // so deref and wrap in Some() for proper return type + Some(x) => Some(*x), None => { - // If a previous base overflowed, just - // pass on the overflow. The overflow will - // be caught later. Using the max value of u128 - // for convenience. - let prev = factorial(n - 1, table) - .unwrap_or(u128::MAX); + // The ? suffix passes along the Option value + // to be handled later + // See: https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator + let prev = factorial(n - 1, table)?; // Do an overflow-checked multiply let attempt = (n as u128).checked_mul(prev); diff --git a/__non-book-expirements__/fibonacci/src/main.rs b/__non-book-expirements__/fibonacci/src/main.rs index 84d5fef..e636c95 100644 --- a/__non-book-expirements__/fibonacci/src/main.rs +++ b/__non-book-expirements__/fibonacci/src/main.rs @@ -5,18 +5,16 @@ use separator::Separatable; use std::io; use std::u128; -///! Calculate a number in the fibonnacci sequence, +///! Calculate a number in the fibonacci sequence, ///! using a lookup table for better worst-case performance. /// /// Can calculate up to 186 using native unsigned 128 bit integers. fn fibonacci(n: usize, table: &mut Vec) -> Option { match table.get(n) { - Some(x) => Some(*x), // Vec.get returns a Option with a reference to the value, so deref + Some(x) => Some(*x), None => { - let a = fibonacci(n - 1, table) - .unwrap_or(u128::MAX); - let b = fibonacci(n - 2, table) - .unwrap_or(u128::MAX); + let a = fibonacci(n - 1, table)?; + let b = fibonacci(n - 2, table)?; // Check for overflow when adding let attempt = a.checked_add(b);