im_rc/iter.rs
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5//! Iterators over immutable data.
6
7/// Create an iterator of values using a function to update an owned state
8/// value.
9///
10/// The function is called with the current state as its argument, and should
11/// return an [`Option`][std::option::Option] of a tuple of the next value to
12/// yield from the iterator and the updated state. If the function returns
13/// [`None`][std::option::Option::None], the iterator ends.
14///
15/// # Examples
16/// ```
17/// # #[macro_use] extern crate im_rc as im;
18/// # use im::iter::unfold;
19/// # use im::vector::Vector;
20/// # use std::iter::FromIterator;
21/// // Create an infinite stream of numbers, starting at 0.
22/// let mut it = unfold(0, |i| Some((i, i + 1)));
23///
24/// // Make a list out of its first five elements.
25/// let numbers = Vector::from_iter(it.take(5));
26/// assert_eq!(numbers, vector![0, 1, 2, 3, 4]);
27/// ```
28///
29/// [std::option::Option]: https://doc.rust-lang.org/std/option/enum.Option.html
30/// [std::option::Option::None]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None
31pub fn unfold<F, S, A>(value: S, f: F) -> impl Iterator<Item = A>
32where
33 F: Fn(S) -> Option<(A, S)>,
34{
35 let mut value = Some(value);
36 std::iter::from_fn(move || {
37 f(value.take().unwrap()).map(|(next, state)| {
38 value = Some(state);
39 next
40 })
41 })
42}