Skip to content

Instantly share code, notes, and snippets.

@takscape
Last active August 29, 2015 14:13
Show Gist options
  • Save takscape/275588b96db00174fb4d to your computer and use it in GitHub Desktop.
Save takscape/275588b96db00174fb4d to your computer and use it in GitHub Desktop.
use std::iter::{Iterator, iterate, Map, Unfold};
use std::num::Int;
type FibInternalIter<T> = Map<
(T, T), T,
Unfold<
(T, T), (fn((T, T)) -> (T, T), Option<(T, T)>, bool),
fn(&mut (fn((T, T)) -> (T, T), Option<(T, T)>, bool)) -> Option<(T, T)>>,
fn((T, T)) -> T>;
struct Fib<T> where T: Int {
it : FibInternalIter<T>
}
impl <T> Iterator for Fib<T> where
T: Int,
{
type Item = T;
fn next(&mut self) -> Option<T> {
self.it.next()
}
}
fn step<T>((cur, next): (T, T)) -> (T, T) where T: Int {
(next, cur + next)
}
fn fst<T>((cur, _): (T, T)) -> T where T: Int {
cur
}
fn fib<T>() -> Fib<T> where T: Int {
let iterator = iterate((<T as Int>::zero(), <T as Int>::one()),
step::<T> as fn((T, T)) -> (T, T)).map(fst::<T> as fn((T,T)) -> T);
Fib { it : iterator }
}
fn main() {
let mut it = fib::<i64>().take(10);
for v in it {
println!("{}", v);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment