@@ -2036,18 +2036,49 @@ for Inspect<'a, A, T> {
2036
2036
}
2037
2037
}
2038
2038
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
+ /// ```
2040
2071
#[ experimental]
2041
2072
pub struct Unfold < ' a , A , St > {
2042
2073
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
2044
2075
pub state : St ,
2045
2076
}
2046
2077
2047
2078
#[ experimental]
2048
2079
impl < ' a , A , St > Unfold < ' a , A , St > {
2049
2080
/// 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
2051
2082
#[ inline]
2052
2083
pub fn new < ' a > ( initial_state : St , f: |& mut St |: ' a -> Option <A >)
2053
2084
-> Unfold <' a, A , St > {
0 commit comments