diff --git a/src/libstd/iterator.rs b/src/libstd/iterator.rs index 780a5a827d1..14f161380aa 100644 --- a/src/libstd/iterator.rs +++ b/src/libstd/iterator.rs @@ -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 { /// ~~~ 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>(&mut self) -> B; + /// Loops through `n` iterations, returning the `n`th element of the /// iterator. /// @@ -419,6 +434,11 @@ impl> IteratorUtil for T { iter::to_vec::(|f| self.advance(f)) } + #[inline(always)] + fn collect>(&mut self) -> B { + FromIter::from_iter::(|f| self.advance(f)) + } + /// Return the `n`th item yielded by an iterator. #[inline(always)] fn nth(&mut self, mut n: uint) -> Option { @@ -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];