diff --git a/src/libcore/vec.rs b/src/libcore/vec.rs index 511063bb44f..aa554fa127c 100644 --- a/src/libcore/vec.rs +++ b/src/libcore/vec.rs @@ -846,6 +846,21 @@ pub pure fn filter_map(v: &[T], f: fn(t: &T) -> Option) result } +/** + * Construct a new vector from the elements of a vector for which some + * predicate holds. + * + * Apply function `f` to each element of `v` and return a vector containing + * only those elements for which `f` returned true. + */ +pub fn filter(v: ~[T], f: fn(t: &T) -> bool) -> ~[T] { + let mut result = ~[]; + do v.consume |_, elem| { + if f(&elem) { result.push(elem); } + } + result +} + /** * Construct a new vector from the elements of a vector for which some * predicate holds. @@ -1805,6 +1820,7 @@ pub trait OwnedVector { fn truncate(&mut self, newlen: uint); fn retain(&mut self, f: pure fn(t: &T) -> bool); fn consume(self, f: fn(uint, v: T)); + fn filter(self, f: fn(t: &T) -> bool) -> ~[T]; fn partition(self, f: pure fn(&T) -> bool) -> (~[T], ~[T]); } @@ -1864,6 +1880,11 @@ impl ~[T]: OwnedVector { consume(self, f) } + #[inline] + fn filter(self, f: fn(&T) -> bool) -> ~[T] { + filter(self, f) + } + /** * Partitions the vector into those that satisfies the predicate, and * those that do not.