From 7f7eb7c0a859066136c70d89f951e9224c482bbd Mon Sep 17 00:00:00 2001 From: Corin Lawson Date: Fri, 14 Jun 2019 14:04:06 +1000 Subject: [PATCH] feat(iterators5): Introduce fibonacci exercise Every good programming exercise book should include the fibonacci numbers! One possible solution: (0..i).fold((0, 1), |(a, b), _| (b, a + b)).1 Signed-off-by: Corin Lawson --- .../standard_library_types/iterators5.rs | 61 +++++++++++++++++++ info.toml | 4 ++ 2 files changed, 65 insertions(+) create mode 100644 exercises/standard_library_types/iterators5.rs diff --git a/exercises/standard_library_types/iterators5.rs b/exercises/standard_library_types/iterators5.rs new file mode 100644 index 0000000..ba37a87 --- /dev/null +++ b/exercises/standard_library_types/iterators5.rs @@ -0,0 +1,61 @@ +// iterators5.rs + +pub fn fibonacci(i: u64) -> u64 { + // Complete this function to return the ith fibonacci number + // Do not use: + // - return + // For extra fun don't use: + // - imperative style loops (for, while) + // - let + // For the most fun don't use: + // - recursion + // Scroll down for hints. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fibonacci_of_1() { + assert_eq!(1, fibonacci(1)); + } + #[test] + fn fibonacci_of_2() { + assert_eq!(2, fibonacci(2)); + } + + #[test] + fn fibonacci_up_to_10() { + assert_eq!( + "[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]", + format!("{:?}", (0..10).map(fibonacci).collect::>()) + ); + } +} + + + + + + + + + + + + + + + + + + + + + + +// In an imperative language you might write a for loop to iterate through +// add and keep track of the last two values into a mutable variables. +// Or you might write code more functionally with recursion and a match clause. +// But you can also use ranges and iterators to solve this in rust. diff --git a/info.toml b/info.toml index 2eb34ef..96fa239 100644 --- a/info.toml +++ b/info.toml @@ -217,3 +217,7 @@ mode = "test" [[exercises]] path = "exercises/standard_library_types/iterators4.rs" mode = "test" + +[[exercises]] +path = "exercises/standard_library_types/iterators5.rs" +mode = "test"