Function itertools::unfold

source ·
pub fn unfold<A, St, F>(initial_state: St, f: F) -> Unfold<St, F> 
where F: FnMut(&mut St) -> Option<A>,
Expand description

Creates a new unfold source with the specified closure as the “iterator function” and an initial state to eventually pass to the closure

unfold is a general iterator builder: it has a mutable state value, and a closure with access to the state that produces the next value.

This more or less equivalent to a regular struct with an Iterator implementation, and is useful for one-off iterators.

// an iterator that yields sequential Fibonacci numbers,
// and stops at the maximum representable value.

use itertools::unfold;

let mut fibonacci = unfold((1u32, 1u32), |(x1, x2)| {
    // Attempt to get the next Fibonacci number
    let next = x1.saturating_add(*x2);

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

    // If addition has saturated at the maximum, we are finished
    if ret == *x1 && ret > 1 {
        None
    } else {
        Some(ret)
    }
});

itertools::assert_equal(fibonacci.by_ref().take(8),
                        vec![1, 1, 2, 3, 5, 8, 13, 21]);
assert_eq!(fibonacci.last(), Some(2_971_215_073))