@@ -2036,18 +2036,49 @@ for Inspect<'a, A, T> {
20362036 }
20372037}
20382038
2039- /// An iterator which just modifies the contained state throughout iteration.
2039+ /// An iterator which passes mutable state to a closure and yields the result.
2040+ ///
2041+ /// # Example: The Fibonacci Sequence
2042+ ///
2043+ /// An iterator that yields sequential Fibonacci numbers, and stops on overflow.
2044+ ///
2045+ /// ```rust
2046+ /// use std::iter::Unfold;
2047+ /// use std::num::Int; // For `.checked_add()`
2048+ ///
2049+ /// // This iterator will yield up to the last Fibonacci number before the max value of `u32`.
2050+ /// // You can simply change `u32` to `u64` in this line if you want higher values than that.
2051+ /// let mut fibonacci = Unfold::new((Some(0u32), Some(1u32)), |&(ref mut x2, ref mut x1)| {
2052+ /// // Attempt to get the next Fibonacci number
2053+ /// // `x1` will be `None` if previously overflowed.
2054+ /// let next = match (*x2, *x1) {
2055+ /// (Some(x2), Some(x1)) => x2.checked_add(x1),
2056+ /// _ => None,
2057+ /// };
2058+ ///
2059+ /// // Shift left: ret <- x2 <- x1 <- next
2060+ /// let ret = *x2;
2061+ /// *x2 = *x1;
2062+ /// *x1 = next;
2063+ ///
2064+ /// ret
2065+ /// });
2066+ ///
2067+ /// for i in fibonacci {
2068+ /// println!("{}", i);
2069+ /// }
2070+ /// ```
20402071#[ experimental]
20412072pub struct Unfold < ' a , A , St > {
20422073 f: |& mut St |: ' a -> Option <A >,
2043- /// Internal state that will be yielded on the next iteration
2074+ /// Internal state that will be passed to the closure on the next iteration
20442075 pub state : St ,
20452076}
20462077
20472078#[ experimental]
20482079impl < ' a , A , St > Unfold < ' a , A , St > {
20492080 /// Creates a new iterator with the specified closure as the "iterator
2050- /// function" and an initial state to eventually pass to the iterator
2081+ /// function" and an initial state to eventually pass to the closure
20512082 #[ inline]
20522083 pub fn new < ' a > ( initial_state : St , f: |& mut St |: ' a -> Option <A >)
20532084 -> Unfold <' a, A , St > {
0 commit comments