Created
December 31, 2014 17:51
-
-
Save olistik/73107fb3c1fbad115d09 to your computer and use it in GitHub Desktop.
Which version suits better the example?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This version uses mem::replace() | |
use std::mem; | |
struct Fibonacci { | |
curr: uint, | |
next: uint, | |
} | |
impl Iterator<uint> for Fibonacci { | |
fn next(&mut self) -> Option<uint> { | |
let new_next = self.curr + self.next; | |
let new_curr = mem::replace(&mut self.next, new_next); | |
Some(mem::replace(&mut self.curr, new_curr)) | |
} | |
} | |
fn fibonacci() -> Fibonacci { | |
Fibonacci { curr: 1, next: 1 } | |
} | |
fn main() { | |
println!("The first four terms of the Fibonacci sequence are: "); | |
for i in fibonacci().take(4) { | |
println!("> {}", i); | |
} | |
println!("The next four terms of the Fibonacci sequence are: "); | |
for i in fibonacci().skip(4).take(4) { | |
println!("> {}", i); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This version doesn't use mem::replace() | |
struct Fibonacci { | |
curr: uint, | |
next: uint, | |
} | |
impl Iterator<uint> for Fibonacci { | |
fn next(&mut self) -> Option<uint> { | |
let (new_curr, new_next) = (self.next, self.curr + self.next); | |
self.curr = new_curr; | |
self.next = new_next; | |
Some(self.curr) | |
} | |
} | |
fn fibonacci() -> Fibonacci { | |
Fibonacci { curr: 0, next: 1 } | |
} | |
fn main() { | |
println!("The first four terms of the Fibonacci sequence are: "); | |
for i in fibonacci().take(4) { | |
println!("> {}", i); | |
} | |
println!("The next four terms of the Fibonacci sequence are: "); | |
for i in fibonacci().skip(4).take(4) { | |
println!("> {}", i); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm referring to the iter example