Skip to content

Instantly share code, notes, and snippets.

@erszcz
Created June 15, 2014 14:11
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 erszcz/bc962a68fb5e0eae1b8f to your computer and use it in GitHub Desktop.
Save erszcz/bc962a68fb5e0eae1b8f to your computer and use it in GitHub Desktop.
Lazy Fibonacci generator in Rust
use std::iter::Unfold;
fn main() {
let it = fibonacci();
// prints the sequence
//for i in it.take(10) {
// print!("{} ", i)
//}
// doesn't print anything
it.take(10).inspect(|&i| {
print!("{} ", i)
});
println!("")
}
fn fibonacci() -> Unfold<uint, FibState> {
let st = FibState{curr: 1, next: 2};
Unfold::new(st, fib_next)
}
struct FibState {
curr: uint,
next: uint
}
fn fib_next(st: &mut FibState) -> Option<uint> {
let prev = st.curr;
st.curr = st.next;
st.next = prev + st.next;
Some (prev)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment