diff options
| author | Marvin Löbel <loebel.marvin@gmail.com> | 2013-06-03 23:26:53 +0200 |
|---|---|---|
| committer | Marvin Löbel <loebel.marvin@gmail.com> | 2013-06-06 22:11:47 +0200 |
| commit | af2086a2f1914f5e4db8534b6c0784b612f3a33d (patch) | |
| tree | ac5473900f69f117b68756e6d02a0b6f375a8e8f /src/libstd | |
| parent | 0e9636922410d4c905135e93056fd86f1f49da30 (diff) | |
| download | rust-af2086a2f1914f5e4db8534b6c0784b612f3a33d.tar.gz rust-af2086a2f1914f5e4db8534b6c0784b612f3a33d.zip | |
Added iter::FromIter
Diffstat (limited to 'src/libstd')
| -rw-r--r-- | src/libstd/iter.rs | 34 |
1 files changed, 31 insertions, 3 deletions
diff --git a/src/libstd/iter.rs b/src/libstd/iter.rs index e5d79d79fce..fde27a6fc09 100644 --- a/src/libstd/iter.rs +++ b/src/libstd/iter.rs @@ -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) } /** @@ -269,6 +290,13 @@ mod tests { } #[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]; assert!(any(|&x: &uint| x > 2, |f| xs.each(f))); |
