Skip to content

Instantly share code, notes, and snippets.

@dholbrook
Created August 18, 2016 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dholbrook/0d00f888f18f2fa6fc3676635749d9fe to your computer and use it in GitHub Desktop.
Save dholbrook/0d00f888f18f2fa6fc3676635749d9fe to your computer and use it in GitHub Desktop.
// Fibonacci from http://rustbyexample.com/trait/iter.html
struct Fibonacci {
curr: u32,
next: u32,
}
impl Iterator for Fibonacci {
type Item = u32;
fn next(&mut self) -> Option<u32> {
let new_next = self.curr + self.next;
self.curr = self.next;
self.next = new_next;
Some(self.curr)
}
}
fn fibonacci() -> Fibonacci {
Fibonacci { curr: 1, next: 1 }
}
pub fn euler2() -> u32 {
fibonacci()
.take_while(|n: &u32| *n < 4000000)
.filter(|n: &u32| *n % 2 == 0)
.fold(0, |acc: u32, n: u32| acc + n)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment