Created
January 31, 2017 18:53
-
-
Save tesaguri/75f14e124a9f7b23c707bc592b08c48c to your computer and use it in GitHub Desktop.
Create an iterator from a closure representing a recurrence relation.
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
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