Implementing a Lazy Sequence Generator in Rust
Generators are powerful tools for creating sequences of values on demand, efficiently handling potentially large or infinite data streams without consuming excessive memory. This challenge focuses on implementing a custom generator in Rust that produces a sequence of numbers based on a specific pattern.
Problem Description
Your task is to implement a generator function in Rust that produces a sequence of numbers. This generator will be a "lazy" sequence, meaning it will only compute and yield the next value when requested. The sequence should follow a specific rule: each subsequent number is the sum of the two preceding numbers, starting with 0 and 1. This is the Fibonacci sequence.
You will need to:
- Create a function that acts as a generator.
- This generator should yield
u64values. - The sequence should start with 0, then 1.
- Subsequent numbers should be the sum of the two previous numbers.
- The generator should be able to produce a large number of Fibonacci numbers without issues.
Expected Behavior:
When iterating over the generator, it should produce: 0, 1, 1, 2, 3, 5, 8, 13, and so on.
Edge Cases to Consider:
- What happens when the Fibonacci numbers become very large and exceed the capacity of
u64? (While not strictly required to handle overflow, be aware of its potential). - The initial two values (0 and 1) are the base cases for the recursion.
Examples
Example 1: Input: Requesting the first 5 numbers from the generator. Output:
0
1
1
2
3
Explanation: The generator produces the first five numbers of the Fibonacci sequence: 0, 1, 1, 2, 3.
Example 2: Input: Requesting the first 10 numbers from the generator. Output:
0
1
1
2
3
5
8
13
21
34
Explanation: The generator produces the first ten numbers of the Fibonacci sequence.
Constraints
- The generator must produce
u64values. - The implementation should be efficient in terms of memory usage.
- The generator should be capable of producing at least 93 Fibonacci numbers before potential overflow of
u64.
Notes
Rust's Iterator trait is fundamental to implementing generators. Consider how you can maintain state (the last two Fibonacci numbers) between calls to next(). You might explore using structs to hold this state and implement Iterator for them. The yield keyword is not directly available in stable Rust as it is in some other languages; you'll need to achieve generator-like behavior through the Iterator trait.