Skip to content

Commit af2086a

Browse files
committed
Added iter::FromIter
1 parent 0e96369 commit af2086a

File tree

1 file changed

+31
-3
lines changed

1 file changed

+31
-3
lines changed

src/libstd/iter.rs

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,29 @@ pub trait Times {
5151
fn times(&self, it: &fn() -> bool) -> bool;
5252
}
5353

54+
pub trait FromIter<T> {
55+
// Build a container with elements from an internal iterator.
56+
//
57+
// # Example:
58+
//
59+
// ~~~ {.rust}
60+
// let xs = ~[1, 2, 3];
61+
// let ys: ~[int] = do FromIter::from_iter |f| { xs.each(|x| f(*x)) };
62+
// assert_eq!(xs, ys);
63+
// ~~~
64+
pub fn from_iter(iter: &fn(f: &fn(T) -> bool) -> bool) -> Self;
65+
}
66+
67+
// NOTE: This should be in vec but can't because of coherence
68+
impl<T> FromIter<T> for ~[T]{
69+
#[inline(always)]
70+
pub fn from_iter(iter: &fn(f: &fn(T) -> bool) -> bool) -> ~[T] {
71+
let mut v = ~[];
72+
for iter |x| { v.push(x) }
73+
v
74+
}
75+
}
76+
5477
/**
5578
* Transform an internal iterator into an owned vector.
5679
*
@@ -64,9 +87,7 @@ pub trait Times {
6487
*/
6588
#[inline(always)]
6689
pub fn to_vec<T>(iter: &fn(f: &fn(T) -> bool) -> bool) -> ~[T] {
67-
let mut v = ~[];
68-
for iter |x| { v.push(x) }
69-
v
90+
FromIter::from_iter(iter)
7091
}
7192

7293
/**
@@ -268,6 +289,13 @@ mod tests {
268289
assert_eq!(xs, ys);
269290
}
270291

292+
#[test]
293+
fn test_from_iter() {
294+
let xs: ~[int] = ~[1, 2, 3];
295+
let ys: ~[int] = do FromIter::from_iter |f| { xs.each(|x| f(*x)) };
296+
assert_eq!(xs, ys);
297+
}
298+
271299
#[test]
272300
fn test_any() {
273301
let xs = ~[1u, 2, 3, 4, 5];

0 commit comments

Comments
 (0)