Added iter::FromIter

This commit is contained in:
Marvin Löbel 2013-06-03 23:26:53 +02:00
parent 0e96369224
commit af2086a2f1
1 changed files with 31 additions and 3 deletions

View File

@ -51,6 +51,29 @@ pub trait Times {
fn times(&self, it: &fn() -> bool) -> bool;
}
pub trait FromIter<T> {
// Build a container with elements from an internal iterator.
//
// # Example:
//
// ~~~ {.rust}
// let xs = ~[1, 2, 3];
// let ys: ~[int] = do FromIter::from_iter |f| { xs.each(|x| f(*x)) };
// assert_eq!(xs, ys);
// ~~~
pub fn from_iter(iter: &fn(f: &fn(T) -> bool) -> bool) -> Self;
}
// NOTE: This should be in vec but can't because of coherence
impl<T> FromIter<T> for ~[T]{
#[inline(always)]
pub fn from_iter(iter: &fn(f: &fn(T) -> bool) -> bool) -> ~[T] {
let mut v = ~[];
for iter |x| { v.push(x) }
v
}
}
/**
* Transform an internal iterator into an owned vector.
*
@ -64,9 +87,7 @@ pub trait Times {
*/
#[inline(always)]
pub fn to_vec<T>(iter: &fn(f: &fn(T) -> bool) -> bool) -> ~[T] {
let mut v = ~[];
for iter |x| { v.push(x) }
v
FromIter::from_iter(iter)
}
/**
@ -268,6 +289,13 @@ mod tests {
assert_eq!(xs, ys);
}
#[test]
fn test_from_iter() {
let xs: ~[int] = ~[1, 2, 3];
let ys: ~[int] = do FromIter::from_iter |f| { xs.each(|x| f(*x)) };
assert_eq!(xs, ys);
}
#[test]
fn test_any() {
let xs = ~[1u, 2, 3, 4, 5];