Skip to content

Instantly share code, notes, and snippets.

@victor-iyi
Created December 13, 2020 01:37
Show Gist options
  • Save victor-iyi/1c74591c33bdd9c45f49b87152ce5d79 to your computer and use it in GitHub Desktop.
Save victor-iyi/1c74591c33bdd9c45f49b87152ce5d79 to your computer and use it in GitHub Desktop.
Implementing the fibonacci series using Rust's Iterator
// Author: Victor I. Afolabi
// Implementing the Fibonacci series using Rust's Iterator
#[derive(Debug, PartialEq, PartialOrd)]
pub struct Fib {
current: usize,
next: usize,
}
impl Fib {
pub fn new() -> Fib {
Fib::default()
}
pub fn n_fib(n: usize) -> Vec<usize> {
Fib::default().take(n).collect::<Vec<usize>>()
}
}
impl Default for Fib {
fn default() -> Fib {
Fib {
current: 1,
next: 1,
}
}
}
impl Iterator for Fib {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
let next: Self::Item = self.current + self.next;
self.current = self.next;
self.next = next;
Some(next)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn default() {
let n_fib: Vec<usize> = Fib::default().take(5).collect::<Vec<usize>>();
assert_eq!(n_fib, [2, 3, 5, 8, 13]);
}
#[test]
fn next() {
let mut f = Fib::new();
assert_eq!(f.next(), Some(2));
assert_eq!(f.next(), Some(3));
assert_eq!(f.next(), Some(5));
assert_eq!(f.next(), Some(8));
}
#[test]
fn n_fib() {
let n_fib = Fib::n_fib(5);
assert_eq!(n_fib, [2, 3, 5, 8, 13]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment