Skip to content

Commit ed54162

Browse files
author
Jakub Wieczorek
committed
Add an iterate function to core::iter
Implementation by Kevin Ballard. The function returns an Unfold iterator producing an infinite stream of results of repeated applications of the function, starting from the provided seed value.
1 parent 88231a9 commit ed54162

File tree

2 files changed

+34
-4
lines changed

2 files changed

+34
-4
lines changed

src/libcore/iter.rs

+25-4
Original file line numberDiff line numberDiff line change
@@ -64,14 +64,14 @@ the rest of the rust manuals.
6464
6565
*/
6666

67+
use clone::Clone;
6768
use cmp;
69+
use cmp::{PartialEq, PartialOrd, Ord};
70+
use mem;
6871
use num::{Zero, One, CheckedAdd, CheckedSub, Saturating, ToPrimitive, Int};
69-
use option::{Option, Some, None};
7072
use ops::{Add, Mul, Sub};
71-
use cmp::{PartialEq, PartialOrd, Ord};
72-
use clone::Clone;
73+
use option::{Option, Some, None};
7374
use uint;
74-
use mem;
7575

7676
/// Conversion from an `Iterator`
7777
pub trait FromIterator<A> {
@@ -2192,6 +2192,27 @@ impl<A: Clone> RandomAccessIterator<A> for Repeat<A> {
21922192
fn idx(&mut self, _: uint) -> Option<A> { Some(self.element.clone()) }
21932193
}
21942194

2195+
type IterateState<'a, T> = (|T|: 'a -> T, Option<T>, bool);
2196+
2197+
/// An iterator that repeatedly applies a given function, starting
2198+
/// from a given seed value.
2199+
pub type Iterate<'a, T> = Unfold<'a, T, IterateState<'a, T>>;
2200+
2201+
/// Creates a new iterator that produces an infinite sequence of
2202+
/// repeated applications of the given function `f`.
2203+
#[allow(visible_private_types)]
2204+
pub fn iterate<'a, T: Clone>(f: |T|: 'a -> T, seed: T) -> Iterate<'a, T> {
2205+
Unfold::new((f, Some(seed), true), |st| {
2206+
let &(ref mut f, ref mut val, ref mut first) = st;
2207+
if *first {
2208+
*first = false;
2209+
} else {
2210+
val.mutate(|x| (*f)(x));
2211+
}
2212+
val.clone()
2213+
})
2214+
}
2215+
21952216
/// Functions for lexicographical ordering of sequences.
21962217
///
21972218
/// Lexicographical ordering through `<`, `<=`, `>=`, `>` requires

src/libcoretest/iter.rs

+9
Original file line numberDiff line numberDiff line change
@@ -833,3 +833,12 @@ fn test_min_max_result() {
833833
let r = MinMax(1i,2);
834834
assert_eq!(r.into_option(), Some((1,2)));
835835
}
836+
837+
#[test]
838+
fn test_iterate() {
839+
let mut it = iterate(|x| x * 2, 1u);
840+
assert_eq!(it.next(), Some(1u));
841+
assert_eq!(it.next(), Some(2u));
842+
assert_eq!(it.next(), Some(4u));
843+
assert_eq!(it.next(), Some(8u));
844+
}

0 commit comments

Comments
 (0)