Added IteratorUtil::collect
This commit is contained in:
parent
af2086a2f1
commit
857d433b9a
@ -19,6 +19,7 @@ implementing the `Iterator` trait.
|
||||
|
||||
use cmp;
|
||||
use iter;
|
||||
use iter::FromIter;
|
||||
use num::{Zero, One};
|
||||
use prelude::*;
|
||||
|
||||
@ -255,6 +256,20 @@ pub trait IteratorUtil<A> {
|
||||
/// ~~~
|
||||
fn to_vec(&mut self) -> ~[A];
|
||||
|
||||
/// Loops through the entire iterator, collecting all of the elements into
|
||||
/// a container implementing `FromIter`.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ~~~ {.rust}
|
||||
/// use std::iterator::*;
|
||||
///
|
||||
/// let a = [1, 2, 3, 4, 5];
|
||||
/// let b: ~[int] = a.iter().transform(|&x| x).collect();
|
||||
/// assert!(a == b);
|
||||
/// ~~~
|
||||
fn collect<B: FromIter<A>>(&mut self) -> B;
|
||||
|
||||
/// Loops through `n` iterations, returning the `n`th element of the
|
||||
/// iterator.
|
||||
///
|
||||
@ -419,6 +434,11 @@ impl<A, T: Iterator<A>> IteratorUtil<A> for T {
|
||||
iter::to_vec::<A>(|f| self.advance(f))
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn collect<B: FromIter<A>>(&mut self) -> B {
|
||||
FromIter::from_iter::<A, B>(|f| self.advance(f))
|
||||
}
|
||||
|
||||
/// Return the `n`th item yielded by an iterator.
|
||||
#[inline(always)]
|
||||
fn nth(&mut self, mut n: uint) -> Option<A> {
|
||||
@ -1062,6 +1082,13 @@ mod tests {
|
||||
assert_eq!(v.slice(0, 0).iter().transform(|&x| x).min(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_collect() {
|
||||
let a = [1, 2, 3, 4, 5];
|
||||
let b: ~[int] = a.iter().transform(|&x| x).collect();
|
||||
assert_eq!(a, b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_all() {
|
||||
let v = ~&[1, 2, 3, 4, 5];
|
||||
|
Loading…
x
Reference in New Issue
Block a user