Fib iterator

Published 330d ago

 ayebear

A Fibonacci sequence iterator that can efficiently generate each number in a single operation each next() call.

struct Fib(f64, f64);

impl Iterator for Fib {
    type Item = f64;
    fn next(&mut self) -> Option<Self::Item> {
        *self = Self(self.1, self.0 + self.1);
        Some(self.0)
    }
}

fn fib() -> Fib {
    Fib(0., 1.)
}

fn main() {
    for i in fib().take(100) {
        println!("{i}");
    }
}

iteratorsfunctionalfpfibfibonaccigeneratoriteriterator
1

Please login or sign up to comment and collaborate