Struct std::iter::UnfoldUnstable [-] [+] [src]

pub struct Unfold<St, F> {
    pub state: St,
    // some fields omitted
}

An iterator that passes mutable state to a closure and yields the result.

Example: The Fibonacci Sequence

An iterator that yields sequential Fibonacci numbers, and stops on overflow.

fn main() { use std::iter::Unfold; use std::num::Int; // For `.checked_add()` // This iterator will yield up to the last Fibonacci number before the max // value of `u32`. You can simply change `u32` to `u64` in this line if // you want higher values than that. let mut fibonacci = Unfold::new((Some(0u32), Some(1u32)), |&mut (ref mut x2, ref mut x1)| { // Attempt to get the next Fibonacci number // `x1` will be `None` if previously overflowed. let next = match (*x2, *x1) { (Some(x2), Some(x1)) => x2.checked_add(x1), _ => None, }; // Shift left: ret <- x2 <- x1 <- next let ret = *x2; *x2 = *x1; *x1 = next; ret }); for i in fibonacci { println!("{}", i); } }
use std::iter::Unfold;
use std::num::Int; // For `.checked_add()`

// This iterator will yield up to the last Fibonacci number before the max
// value of `u32`. You can simply change `u32` to `u64` in this line if
// you want higher values than that.
let mut fibonacci = Unfold::new((Some(0u32), Some(1u32)),
                                |&mut (ref mut x2, ref mut x1)| {
    // Attempt to get the next Fibonacci number
    // `x1` will be `None` if previously overflowed.
    let next = match (*x2, *x1) {
        (Some(x2), Some(x1)) => x2.checked_add(x1),
        _ => None,
    };

    // Shift left: ret <- x2 <- x1 <- next
    let ret = *x2;
    *x2 = *x1;
    *x1 = next;

    ret
});

for i in fibonacci {
    println!("{}", i);
}

Fields

state

Internal state that will be passed to the closure on the next iteration

Methods

impl<A, St, F> Unfold<St, F> where F: FnMut(&mut St), <F as FnMut(&mut St)>::Output == Option<A>

fn new(initial_state: St, f: F) -> Unfold<St, F>

Creates a new iterator with the specified closure as the "iterator function" and an initial state to eventually pass to the closure

Trait Implementations

impl<A, St, F> Iterator for Unfold<St, F> where F: FnMut(&mut St), <F as FnMut(&mut St)>::Output == Option<A>

type Item = A

fn next(&mut self) -> Option<A>

fn size_hint(&self) -> (usize, Option<usize>)

fn size_hint(&self) -> (usize, Option<usize>)

Derived Implementations

impl<St, F> Clone for Unfold<St, F> where St: Clone, F: Clone

fn clone(&self) -> Unfold<St, F>

fn clone_from(&mut self, &Unfold<St, F>)