mirror of
https://github.com/rust-lang/rust.git
synced 2024-12-13 00:56:14 +00:00
Added iter::FromIter
This commit is contained in:
parent
0e96369224
commit
af2086a2f1
@ -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];
|
||||
|
Loading…
Reference in New Issue
Block a user