Implement Iterator for a Fibonacci struct and use take, filter and sum on it
Write Fib, an endless iterator over the Fibonacci numbers 0, 1, 1, 2, 3, 5, …, and use it in even_sum_first_10, which returns the sum of the even numbers among the first 10 of them.
Requirements:
- Implement only
nextandtype Item = u64;take,filterandsummust come from the trait as they are. Fib::new().take(10)yields0, 1, 1, 2, 3, 5, 8, 13, 21, 34, so the function returns44.- No
Vecor other buffer: the struct holds only the state it needs for the next number.
struct Fib {
// your fields here
}
impl Fib {
fn new() -> Self {
// your code here
}
}
impl Iterator for Fib {
type Item = u64;
fn next(&mut self) -> Option<u64> {
// your code here
}
}
fn even_sum_first_10() -> u64 {
// your code here
}Write the implementation.
Do not add extra use lines unless the task says so explicitly.
Keep the state (a, b) in the struct, set type Item = u64 and write only next: return Some(a) and shift to (b, a + b). take, filter and sum are default methods built on next; the even ones among the first 10 sum to 44.
- Implementing
takeorfilterby hand, though they are default methods built onnext - Buffering the sequence in a
Vec, which throws laziness away and cannot be endless - Forgetting that
a + boverflowsu64on the 93rd call tonextand panics in a debug build
- How would you make
Fibend withNoneinstead of panicking on overflow? - Why does
for n in Fib::new()work without anIntoIteratorimpl forFib?
An iterator needs the state that produces its next element; for Fibonacci that is the last two numbers. next returns the current a and moves the pair one step forward. Nothing else has to be written: the Iterator trait has one required method, and take, filter, sum, skip and dozens more are default methods built on next.
struct Fib {
a: u64,
b: u64,
}
impl Fib {
fn new() -> Self {
Fib { a: 0, b: 1 }
}
}
impl Iterator for Fib {
type Item = u64;
fn next(&mut self) -> Option<u64> {
let n = self.a;
self.a = self.b;
self.b += n; // the new pair: (b, a + b)
Some(n)
}
}
fn even_sum_first_10() -> u64 {
Fib::new().take(10).filter(|n| n % 2 == 0).sum()
}
fn main() {
let first: Vec<u64> = Fib::new().take(10).collect();
println!("{first:?}"); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
println!("{}", even_sum_first_10()); // 44
for n in Fib::new().skip(5).take(3) {
print!("{n} "); // 5 8 13
}
println!();
}Fib is endless: next never returns None, so without take or take_while a call to sum never finishes. The even numbers among the first 10 are 0, 2, 8 and 34, which sum to 44. The loop for n in Fib::new() works without an IntoIterator impl of its own: the standard library implements it for every type that implements Iterator.
The u64 limit comes quickly. The struct computes the number two steps ahead, so in a debug build the 93rd call to next already panics with attempt to add with overflow, even though the number it would return still fits in a u64. To end the sequence instead of panicking, keep the upcoming numbers as Option<u64> and compute them with checked_add.