Composable external iterators

The Iterator trait defines an interface for objects which implement iteration as a state machine.

Algorithms like zip are provided as Iterator implementations which wrap other objects implementing the Iterator trait.

Struct ChainIterator

pub struct ChainIterator<A, T, U> {
    priv a: T,
    priv b: U,
    priv flag: bool,
}

An iterator which strings two iterators together

Struct Counter

pub struct Counter<A> {
    /// The current state the counter is at (next value to be yielded)
    state: A,
    /// The amount that this iterator is stepping by
    step: A,
}

An infinite iterator starting at start and advancing by step with each iteration

Struct EnumerateIterator

pub struct EnumerateIterator<A, T> {
    priv iter: T,
    priv count: uint,
}

An iterator which yields the current count and the element during iteration

Struct FilterIterator

pub struct FilterIterator<'self, A, T> {
    priv iter: T,
    priv predicate: &'self fn(&A) -> bool,
}

An iterator which filters the elements of iter with predicate

Struct FilterMapIterator

pub struct FilterMapIterator<'self, A, B, T> {
    priv iter: T,
    priv f: &'self fn(A) -> Option<B>,
}

An iterator which uses f to both filter and map elements from iter

Struct FlatMapIterator

pub struct FlatMapIterator<'self, A, B, T, U> {
    priv iter: T,
    priv f: &'self fn(A) -> U,
    priv subiter: Option<U>,
}

An iterator that maps each element to an iterator, and yields the elements of the produced iterators

Struct MapIterator

pub struct MapIterator<'self, A, B, T> {
    priv iter: T,
    priv f: &'self fn(A) -> B,
}

An iterator which maps the values of iter with f

Struct ScanIterator

pub struct ScanIterator<'self, A, B, T, St> {
    priv iter: T,
    priv f: &'self fn(&mut St, A) -> Option<B>,
    /// The current internal state to be passed to the closure next.
    state: St,
}

An iterator to maintain state while iterating another iterator

Struct SkipIterator

pub struct SkipIterator<A, T> {
    priv iter: T,
    priv n: uint,
}

An iterator which skips over n elements of iter.

Struct SkipWhileIterator

pub struct SkipWhileIterator<'self, A, T> {
    priv iter: T,
    priv flag: bool,
    priv predicate: &'self fn(&A) -> bool,
}

An iterator which rejects elements while predicate is true

Struct TakeIterator

pub struct TakeIterator<A, T> {
    priv iter: T,
    priv n: uint,
}

An iterator which only iterates over the first n iterations of iter.

Struct TakeWhileIterator

pub struct TakeWhileIterator<'self, A, T> {
    priv iter: T,
    priv flag: bool,
    priv predicate: &'self fn(&A) -> bool,
}

An iterator which only accepts elements while predicate is true

Struct UnfoldrIterator

pub struct UnfoldrIterator<'self, A, St> {
    priv f: &'self fn(&mut St) -> Option<A>,
    /// Internal state that will be yielded on the next iteration
    state: St,
}

An iterator which just modifies the contained state throughout iteration.

Struct ZipIterator

pub struct ZipIterator<A, T, B, U> {
    priv a: T,
    priv b: U,
}

An iterator which iterates two other iterators simultaneously

Trait AdditiveIterator

A trait for iterators over elements which can be added together

Method sum

fn sum(&mut self) -> A

Iterates over the entire iterator, summing up all the elements

Example

let a = [1, 2, 3, 4, 5];
let mut it = a.iter().transform(|&x| x);
assert!(it.sum() == 15);

Trait FromIterator

Conversion from an Iterator

Method from_iterator

fn from_iterator(iterator: &mut T) -> Self

Build a container with elements from an external iterator.

Trait Iterator

An interface for dealing with "external iterators". These types of iterators can be resumed at any time as all state is stored internally as opposed to being located on the call stack.

Method next

fn next(&mut self) -> Option<A>

Advance the iterator and return the next value. Return None when the end is reached.

Method size_hint

fn size_hint(&self) -> (Option<uint>, Option<uint>)

Return a lower bound and upper bound on the remaining length of the iterator.

The common use case for the estimate is pre-allocating space to store the results.

Trait IteratorUtil

Iterator adaptors provided for every Iterator implementation. The adaptor objects are also implementations of the Iterator trait.

In the future these will be default methods instead of a utility trait.

Method chain_

fn chain_<U: Iterator<A>>(self, other: U) -> ChainIterator<A, Self, U>

Chain this iterator with another, returning a new iterator which will finish iterating over the current iterator, and then it will iterate over the other specified iterator.

Example

let a = [0];
let b = [1];
let mut it = a.iter().chain_(b.iter());
assert_eq!(it.next().get(), &0);
assert_eq!(it.next().get(), &1);
assert!(it.next().is_none());

Method zip

fn zip<B, U: Iterator<B>>(self, other: U) -> ZipIterator<A, Self, B, U>

Creates an iterator which iterates over both this and the specified iterators simultaneously, yielding the two elements as pairs. When either iterator returns None, all further invocations of next() will return None.

Example

let a = [0];
let b = [1];
let mut it = a.iter().zip(b.iter());
assert_eq!(it.next().get(), (&0, &1));
assert!(it.next().is_none());

Method transform

fn transform<'r, B>(self, f: &'r fn(A) -> B) -> MapIterator<'r, A, B, Self>

Creates a new iterator which will apply the specified function to each element returned by the first, yielding the mapped element instead.

Example

let a = [1, 2];
let mut it = a.iter().transform(|&x| 2 * x);
assert_eq!(it.next().get(), 2);
assert_eq!(it.next().get(), 4);
assert!(it.next().is_none());

Method filter

fn filter<'r>(self, predicate: &'r fn(&A) -> bool) ->
 FilterIterator<'r, A, Self>

Creates an iterator which applies the predicate to each element returned by this iterator. Only elements which have the predicate evaluate to true will be yielded.

Example

let a = [1, 2];
let mut it = a.iter().filter(|&x| *x > 1);
assert_eq!(it.next().get(), &2);
assert!(it.next().is_none());

Method filter_map

fn filter_map<'r, B>(self, f: &'r fn(A) -> Option<B>) ->
 FilterMapIterator<'r, A, B, Self>

Creates an iterator which both filters and maps elements. If the specified function returns None, the element is skipped. Otherwise the option is unwrapped and the new value is yielded.

Example

let a = [1, 2];
let mut it = a.iter().filter_map(|&x| if x > 1 {Some(2 * x)} else {None});
assert_eq!(it.next().get(), 4);
assert!(it.next().is_none());

Method enumerate

fn enumerate(self) -> EnumerateIterator<A, Self>

Creates an iterator which yields a pair of the value returned by this iterator plus the current index of iteration.

Example

let a = [100, 200];
let mut it = a.iter().enumerate();
assert_eq!(it.next().get(), (0, &100));
assert_eq!(it.next().get(), (1, &200));
assert!(it.next().is_none());

Method skip_while

fn skip_while<'r>(self, predicate: &'r fn(&A) -> bool) ->
 SkipWhileIterator<'r, A, Self>

Creates an iterator which invokes the predicate on elements until it returns false. Once the predicate returns false, all further elements are yielded.

Example

let a = [1, 2, 3, 2, 1];
let mut it = a.iter().skip_while(|&a| *a < 3);
assert_eq!(it.next().get(), &3);
assert_eq!(it.next().get(), &2);
assert_eq!(it.next().get(), &1);
assert!(it.next().is_none());

Method take_while

fn take_while<'r>(self, predicate: &'r fn(&A) -> bool) ->
 TakeWhileIterator<'r, A, Self>

Creates an iterator which yields elements so long as the predicate returns true. After the predicate returns false for the first time, no further elements will be yielded.

Example

let a = [1, 2, 3, 2, 1];
let mut it = a.iter().take_while(|&a| *a < 3);
assert_eq!(it.next().get(), &1);
assert_eq!(it.next().get(), &2);
assert!(it.next().is_none());

Method skip

fn skip(self, n: uint) -> SkipIterator<A, Self>

Creates an iterator which skips the first n elements of this iterator, and then it yields all further items.

Example

let a = [1, 2, 3, 4, 5];
let mut it = a.iter().skip(3);
assert_eq!(it.next().get(), &4);
assert_eq!(it.next().get(), &5);
assert!(it.next().is_none());

Method take_

fn take_(self, n: uint) -> TakeIterator<A, Self>

Creates an iterator which yields the first n elements of this iterator, and then it will always return None.

Example

let a = [1, 2, 3, 4, 5];
let mut it = a.iter().take_(3);
assert_eq!(it.next().get(), &1);
assert_eq!(it.next().get(), &2);
assert_eq!(it.next().get(), &3);
assert!(it.next().is_none());

Method scan

fn scan<'r, St,
        B>(self, initial_state: St, f: &'r fn(&mut St, A) -> Option<B>) ->
 ScanIterator<'r, A, B, Self, St>

Creates a new iterator which behaves in a similar fashion to foldl. There is a state which is passed between each iteration and can be mutated as necessary. The yielded values from the closure are yielded from the ScanIterator instance when not None.

Example

let a = [1, 2, 3, 4, 5];
let mut it = a.iter().scan(1, |fac, &x| {
  *fac = *fac * x;
  Some(*fac)
});
assert_eq!(it.next().get(), 1);
assert_eq!(it.next().get(), 2);
assert_eq!(it.next().get(), 6);
assert_eq!(it.next().get(), 24);
assert_eq!(it.next().get(), 120);
assert!(it.next().is_none());

Method flat_map_

fn flat_map_<'r, B, U: Iterator<B>>(self, f: &'r fn(A) -> U) ->
 FlatMapIterator<'r, A, B, Self, U>

Creates an iterator that maps each element to an iterator, and yields the elements of the produced iterators

Example

let xs = [2u, 3];
let ys = [0u, 1, 0, 1, 2];
let mut it = xs.iter().flat_map_(|&x| Counter::new(0u, 1).take_(x));
// Check that `it` has the same elements as `ys`
let mut i = 0;
for it.advance |x: uint| {
    assert_eq!(x, ys[i]);
    i += 1;
}

Method advance

fn advance(&mut self, f: &fn(A) -> bool) -> bool

An adaptation of an external iterator to the for-loop protocol of rust.

Example

use std::iterator::Counter;

for Counter::new(0, 10).advance |i| {
    io::println(fmt!("%d", i));
}

Method collect

fn collect<B: FromIterator<A, Self>>(&mut self) -> B

Loops through the entire iterator, collecting all of the elements into a container implementing FromIterator.

Example

let a = [1, 2, 3, 4, 5];
let b: ~[int] = a.iter().transform(|&x| x).collect();
assert!(a == b);

Method nth

fn nth(&mut self, n: uint) -> Option<A>

Loops through n iterations, returning the nth element of the iterator.

Example

let a = [1, 2, 3, 4, 5];
let mut it = a.iter();
assert!(it.nth(2).get() == &3);
assert!(it.nth(2) == None);

Method last_

fn last_(&mut self) -> Option<A>

Loops through the entire iterator, returning the last element of the iterator.

Example

let a = [1, 2, 3, 4, 5];
assert!(a.iter().last().get() == &5);

Method fold

fn fold<B>(&mut self, start: B, f: &fn(B, A) -> B) -> B

Performs a fold operation over the entire iterator, returning the eventual state at the end of the iteration.

Example

let a = [1, 2, 3, 4, 5];
assert!(a.iter().fold(0, |a, &b| a + b) == 15);

Method len_

fn len_(&mut self) -> uint

Counts the number of elements in this iterator.

Example

let a = [1, 2, 3, 4, 5];
let mut it = a.iter();
assert!(it.len_() == 5);
assert!(it.len_() == 0);

Method all

fn all(&mut self, f: &fn(A) -> bool) -> bool

Tests whether the predicate holds true for all elements in the iterator.

Example

let a = [1, 2, 3, 4, 5];
assert!(a.iter().all(|&x| *x > 0));
assert!(!a.iter().all(|&x| *x > 2));

Method any_

fn any_(&mut self, f: &fn(A) -> bool) -> bool

Tests whether any element of an iterator satisfies the specified predicate.

Example

let a = [1, 2, 3, 4, 5];
let mut it = a.iter();
assert!(it.any_(|&x| *x == 3));
assert!(!it.any_(|&x| *x == 3));

Method find_

fn find_(&mut self, predicate: &fn(&A) -> bool) -> Option<A>

Return the first element satisfying the specified predicate

Method position_

fn position_(&mut self, predicate: &fn(A) -> bool) -> Option<uint>

Return the index of the first element satisfying the specified predicate

Method count

fn count(&mut self, predicate: &fn(A) -> bool) -> uint

Count the number of elements satisfying the specified predicate

Method max_by

fn max_by<B: Ord>(&mut self, f: &fn(&A) -> B) -> Option<A>

Return the element that gives the maximum value from the specfied function

Example

let xs = [-3, 0, 1, 5, -10];
assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);

Method min_by

fn min_by<B: Ord>(&mut self, f: &fn(&A) -> B) -> Option<A>

Return the element that gives the minimum value from the specfied function

Example

let xs = [-3, 0, 1, 5, -10];
assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);

Trait MultiplicativeIterator

A trait for iterators over elements whose elements can be multiplied together.

Method product

fn product(&mut self) -> A

Iterates over the entire iterator, multiplying all the elements

Example

use std::iterator::Counter;

fn factorial(n: uint) -> uint {
    Counter::new(1u, 1).take_while(|&i| i <= n).product()
}
assert!(factorial(0) == 1);
assert!(factorial(1) == 1);
assert!(factorial(5) == 120);

Trait OrdIterator

A trait for iterators over elements which can be compared to one another. The type of each element must ascribe to the Ord trait.

Method max

fn max(&mut self) -> Option<A>

Consumes the entire iterator to return the maximum element.

Example

let a = [1, 2, 3, 4, 5];
assert!(a.iter().max().get() == &5);

Method min

fn min(&mut self) -> Option<A>

Consumes the entire iterator to return the minimum element.

Example

let a = [1, 2, 3, 4, 5];
assert!(a.iter().min().get() == &1);

Implementation of IteratorUtil<A> for T where <A, T: Iterator<A>>

Iterator adaptors provided for every Iterator implementation. The adaptor objects are also implementations of the Iterator trait.

In the future these will be default methods instead of a utility trait.

Method chain_

fn chain_<U: Iterator<A>>(self, other: U) -> ChainIterator<A, T, U>

Method zip

fn zip<B, U: Iterator<B>>(self, other: U) -> ZipIterator<A, T, B, U>

Method transform

fn transform<'r, B>(self, f: &'r fn(A) -> B) -> MapIterator<'r, A, B, T>

Method filter

fn filter<'r>(self, predicate: &'r fn(&A) -> bool) -> FilterIterator<'r, A, T>

Method filter_map

fn filter_map<'r, B>(self, f: &'r fn(A) -> Option<B>) ->
 FilterMapIterator<'r, A, B, T>

Method enumerate

fn enumerate(self) -> EnumerateIterator<A, T>

Method skip_while

fn skip_while<'r>(self, predicate: &'r fn(&A) -> bool) ->
 SkipWhileIterator<'r, A, T>

Method take_while

fn take_while<'r>(self, predicate: &'r fn(&A) -> bool) ->
 TakeWhileIterator<'r, A, T>

Method skip

fn skip(self, n: uint) -> SkipIterator<A, T>

Method take_

fn take_(self, n: uint) -> TakeIterator<A, T>

Method scan

fn scan<'r, St,
        B>(self, initial_state: St, f: &'r fn(&mut St, A) -> Option<B>) ->
 ScanIterator<'r, A, B, T, St>

Method flat_map_

fn flat_map_<'r, B, U: Iterator<B>>(self, f: &'r fn(A) -> U) ->
 FlatMapIterator<'r, A, B, T, U>

Method advance

fn advance(&mut self, f: &fn(A) -> bool) -> bool

A shim implementing the for loop iteration protocol for iterator objects

Method collect

fn collect<B: FromIterator<A, T>>(&mut self) -> B

Method nth

fn nth(&mut self, mut n: uint) -> Option<A>

Return the nth item yielded by an iterator.

Method last_

fn last_(&mut self) -> Option<A>

Return the last item yielded by an iterator.

Method fold

fn fold<B>(&mut self, init: B, f: &fn(B, A) -> B) -> B

Reduce an iterator to an accumulated value

Method len_

fn len_(&mut self) -> uint

Count the number of items yielded by an iterator

Method all

fn all(&mut self, f: &fn(A) -> bool) -> bool

Method any_

fn any_(&mut self, f: &fn(A) -> bool) -> bool

Method find_

fn find_(&mut self, predicate: &fn(&A) -> bool) -> Option<A>

Return the first element satisfying the specified predicate

Method position_

fn position_(&mut self, predicate: &fn(A) -> bool) -> Option<uint>

Return the index of the first element satisfying the specified predicate

Method count

fn count(&mut self, predicate: &fn(A) -> bool) -> uint

Method max_by

fn max_by<B: Ord>(&mut self, f: &fn(&A) -> B) -> Option<A>

Method min_by

fn min_by<B: Ord>(&mut self, f: &fn(&A) -> B) -> Option<A>

Implementation of AdditiveIterator<A> for T where <A: Add<A, A> + Zero, T: Iterator<A>>

Method sum

fn sum(&mut self) -> A

Implementation of MultiplicativeIterator<A> for T where <A: Mul<A, A> + One, T: Iterator<A>>

Method product

fn product(&mut self) -> A

Implementation of OrdIterator<A> for T where <A: Ord, T: Iterator<A>>

Method max

fn max(&mut self) -> Option<A>

Method min

fn min(&mut self) -> Option<A>

Implementation of Iterator<A> for ChainIterator<A, T, U> where <A, T: Iterator<A>, U: Iterator<A>>

Method next

fn next(&mut self) -> Option<A>

Method size_hint

fn size_hint(&self) -> (Option<uint>, Option<uint>)

Implementation of Iterator<(A, B)> for ZipIterator<A, T, B, U> where <A, B, T: Iterator<A>, U: Iterator<B>>

Method next

fn next(&mut self) -> Option<(A, B)>

Implementation of Iterator<B> for MapIterator<'self, A, B, T> where <'self, A, B, T: Iterator<A>>

Method next

fn next(&mut self) -> Option<B>

Method size_hint

fn size_hint(&self) -> (Option<uint>, Option<uint>)

Implementation of Iterator<A> for FilterIterator<'self, A, T> where <'self, A, T: Iterator<A>>

Method next

fn next(&mut self) -> Option<A>

Method size_hint

fn size_hint(&self) -> (Option<uint>, Option<uint>)

Implementation of Iterator<B> for FilterMapIterator<'self, A, B, T> where <'self, A, B, T: Iterator<A>>

Method next

fn next(&mut self) -> Option<B>

Method size_hint

fn size_hint(&self) -> (Option<uint>, Option<uint>)

Implementation of Iterator<(uint, A)> for EnumerateIterator<A, T> where <A, T: Iterator<A>>

Method next

fn next(&mut self) -> Option<(uint, A)>

Implementation of Iterator<A> for SkipWhileIterator<'self, A, T> where <'self, A, T: Iterator<A>>

Method next

fn next(&mut self) -> Option<A>

Implementation of Iterator<A> for TakeWhileIterator<'self, A, T> where <'self, A, T: Iterator<A>>

Method next

fn next(&mut self) -> Option<A>

Implementation of Iterator<A> for SkipIterator<A, T> where <A, T: Iterator<A>>

Method next

fn next(&mut self) -> Option<A>

Implementation of Iterator<A> for TakeIterator<A, T> where <A, T: Iterator<A>>

Method next

fn next(&mut self) -> Option<A>

Implementation of Iterator<B> for ScanIterator<'self, A, B, T, St> where <'self, A, B, T: Iterator<A>, St>

Method next

fn next(&mut self) -> Option<B>

Implementation of Iterator<B> for FlatMapIterator<'self, A, B, T, U> where <'self, A, T: Iterator<A>, B, U: Iterator<B>>

Method next

fn next(&mut self) -> Option<B>

Implementation for UnfoldrIterator<'self, A, St> where <'self, A, St>

Method new

fn new<'a>(initial_state: St, f: &'a fn(&mut St) -> Option<A>) ->
 UnfoldrIterator<'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

Implementation of Iterator<A> for UnfoldrIterator<'self, A, St> where <'self, A, St>

Method next

fn next(&mut self) -> Option<A>

Implementation for Counter<A> where <A>

Method new

fn new(start: A, step: A) -> Counter<A>

Creates a new counter with the specified start/step

Implementation of Iterator<A> for Counter<A> where <A: Add<A, A> + Clone>

Method next

fn next(&mut self) -> Option<A>