Skip to content

Instantly share code, notes, and snippets.

@tesaguri
Created January 31, 2017 18:53
Show Gist options
  • Save tesaguri/75f14e124a9f7b23c707bc592b08c48c to your computer and use it in GitHub Desktop.
Save tesaguri/75f14e124a9f7b23c707bc592b08c48c to your computer and use it in GitHub Desktop.
Create an iterator from a closure representing a recurrence relation.
use std::mem;
struct RecRel<T,F> {
val: T,
succ: F,
}
impl<T,F> RecRel<T,F> {
fn new(init: T, succ: F) -> Self where F: Fn(&T) -> T {
RecRel {
val: init,
succ: succ,
}
}
}
impl<T,F> Iterator for RecRel<T,F> where F: Fn(&T) -> T {
type Item = T;
fn next(&mut self) -> Option<T> {
let next = (self.succ)(&self.val);
Some(mem::replace(&mut self.val, next))
}
}
fn main() {
let fib = RecRel::new((0,1), |&(a,b)| (b,a+b));
for (i,(n,_)) in fib.enumerate().take(10) {
println!("F[{}] = {}", i, n);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment