[−][src]Function itertools::unfold
ⓘImportant traits for Unfold<St, F>
pub fn unfold<A, St, F>(initial_state: St, f: F) -> Unfold<St, F> where
F: FnMut(&mut St) -> Option<A>,
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 x1, mut x2) = (1u32, 1u32); let mut fibonacci = unfold((), move |_| { // 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 { return None; } 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))