diff options
| author | Austin Bonander <austin.bonander@gmail.com> | 2014-12-03 16:31:21 -0800 |
|---|---|---|
| committer | Austin Bonander <austin.bonander@gmail.com> | 2014-12-04 01:28:16 -0800 |
| commit | 2e1911b47ae5a4fd8cf4c4a98e739666f99daf82 (patch) | |
| tree | 6f5cfef92be447fb30fb0d25bc1aa947d7db79b8 /src/libcore | |
| parent | daa0745886c2382c37d5d345f4c5b1b8f7b9a387 (diff) | |
| download | rust-2e1911b47ae5a4fd8cf4c4a98e739666f99daf82.tar.gz rust-2e1911b47ae5a4fd8cf4c4a98e739666f99daf82.zip | |
core::iter::Unfold: reword docs and add example
Remove note about core
Diffstat (limited to 'src/libcore')
| -rw-r--r-- | src/libcore/iter.rs | 37 |
1 files changed, 34 insertions, 3 deletions
diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index 2d488a4b155..6c43d4dbc30 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -2036,18 +2036,49 @@ for Inspect<'a, A, T> { } } -/// An iterator which just modifies the contained state throughout iteration. +/// An iterator which 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. +/// +/// ```rust +/// 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)), |&(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); +/// } +/// ``` #[experimental] pub struct Unfold<'a, A, St> { f: |&mut St|: 'a -> Option<A>, - /// Internal state that will be yielded on the next iteration + /// Internal state that will be passed to the closure on the next iteration pub state: St, } #[experimental] impl<'a, A, St> Unfold<'a, A, St> { /// Creates a new iterator with the specified closure as the "iterator - /// function" and an initial state to eventually pass to the iterator + /// function" and an initial state to eventually pass to the closure #[inline] pub fn new<'a>(initial_state: St, f: |&mut St|: 'a -> Option<A>) -> Unfold<'a, A, St> { |
