fibonacci.rs

View source code here on GitHub!

Includes

use std::ops::{Add,Mul};

use num_traits::{one,zero,One,Zero};

use crate::include::iter_cache::cache_iterator;

pub struct fibonacci::CachingIterator<I, T> where I: Iterator<Item = T> + 'static, T: Clone + 'static

This struct implements a global cache that maps an iterator-iterated pair to a cache of values. It is mostly intended for use with the prime function generator.

pub fn fibonacci::CachingIterator::new() -> CachingIterator<I, T> where I: Iterator<Item = T> + 'static, T: Clone + 'static
pub fn fibonacci::CachingIterator::default() -> CachingIterator<I, T> where I: Iterator<Item = T> + 'static, T: Clone + 'static
pub fn fibonacci::CachingIterator::next() -> Option<T> where T: Clone + 'static
 1use std::ops::{Add,Mul};
 2
 3use num_traits::{one,zero,One,Zero};
 4
 5use crate::include::iter_cache::cache_iterator;
 6
 7pub fn fib<I>() -> impl Iterator<Item = I> where I: Copy + Zero + One + Add + Send + 'static {
 8    return cache_iterator(Fibonacci::<I>::new());
 9}
10
11pub fn fib_by_3<I>() -> impl Iterator<Item = I> where I: Copy + Zero + One + Add + Mul + Send + 'static {
12    return cache_iterator(FibonacciBy3::<I>::new());
13}
14
15#[derive(Clone, Copy, Debug, Hash)]
16pub struct Fibonacci<I> {
17    a: I,
18    b: I,
19}
20
21impl<I> Default for Fibonacci<I> where I: Zero + One {
22    fn default() -> Self {
23        return Fibonacci::<I>{
24            a: zero(),
25            b: one(),
26        };
27    }
28}
29
30impl<I> Fibonacci<I> where I: Zero + One {
31    pub fn new() -> Self {
32        return Default::default();
33    }
34}
35
36impl<I> Iterator for Fibonacci<I> where I: Zero + One + Add + Copy {
37    type Item = I;
38
39    fn next(&mut self) -> Option<Self::Item> {
40        let prior_a = self.a;
41        let prior_b = self.b;
42        self.b = self.a + self.b;
43        self.a = prior_b;
44        return Some(prior_a);
45    }
46}
47
48#[derive(Clone, Copy, Debug, Hash)]
49pub struct FibonacciBy3<I> {
50    a: I,
51    b: I,
52}
53
54impl<I> Default for FibonacciBy3<I> where I: Zero + One + Add + Copy {
55    fn default() -> Self {
56        let two = one::<I>() + one();
57        return FibonacciBy3::<I>{
58            a: zero(),
59            b: two,
60        };
61    }
62}
63
64impl<I> FibonacciBy3<I> where I: Zero + One + Add + Copy {
65    pub fn new() -> Self {
66        return Default::default();
67    }
68}
69
70impl<I> Iterator for FibonacciBy3<I> where I: Zero + One + Add + Mul + Copy {
71    type Item = I;
72
73    fn next(&mut self) -> Option<Self::Item> {
74        let two = one::<I>() + one();
75        let four = two + two;
76        let prior_a = self.a;
77        let prior_b = self.b;
78        self.b = four * self.b + self.a;
79        self.a = prior_b;
80        return Some(prior_a);
81    }
82}