diff options
| author | Daniel Micay <danielmicay@gmail.com> | 2013-06-15 17:42:31 -0400 |
|---|---|---|
| committer | Daniel Micay <danielmicay@gmail.com> | 2013-06-15 17:53:12 -0400 |
| commit | eb5ac84c8e14184b9b76fe088b5f5120e887ee35 (patch) | |
| tree | 6ab431c32fe519a2224b21ae9d1f877559fe75b6 /src/libstd | |
| parent | eac0200f18bfe19646ae5dce56acc325629224cb (diff) | |
| download | rust-eb5ac84c8e14184b9b76fe088b5f5120e887ee35.tar.gz rust-eb5ac84c8e14184b9b76fe088b5f5120e887ee35.zip | |
iterator: add a `find` adaptor
Diffstat (limited to 'src/libstd')
| -rw-r--r-- | src/libstd/iterator.rs | 26 |
1 files changed, 23 insertions, 3 deletions
diff --git a/src/libstd/iterator.rs b/src/libstd/iterator.rs index e65904a6899..7aa273f7cd8 100644 --- a/src/libstd/iterator.rs +++ b/src/libstd/iterator.rs @@ -308,6 +308,9 @@ pub trait IteratorUtil<A> { /// assert!(!it.any_(|&x| *x == 3)); /// ~~~ fn any_(&mut self, f: &fn(A) -> bool) -> bool; + + /// Return the first element satisfying the specified predicate + fn find(&mut self, predicate: &fn(&A) -> bool) -> Option<A>; } /// Iterator adaptors provided for every `Iterator` implementation. The adaptor objects are also @@ -421,7 +424,7 @@ impl<A, T: Iterator<A>> IteratorUtil<A> for T { None => { break; } } } - return accum; + accum } /// Count the number of items yielded by an iterator @@ -431,13 +434,22 @@ impl<A, T: Iterator<A>> IteratorUtil<A> for T { #[inline(always)] fn all(&mut self, f: &fn(A) -> bool) -> bool { for self.advance |x| { if !f(x) { return false; } } - return true; + true } #[inline(always)] fn any_(&mut self, f: &fn(A) -> bool) -> bool { for self.advance |x| { if f(x) { return true; } } - return false; + false + } + + /// Return the first element satisfying the specified predicate + #[inline(always)] + fn find(&mut self, predicate: &fn(&A) -> bool) -> Option<A> { + for self.advance |x| { + if predicate(&x) { return Some(x) } + } + None } } @@ -1055,4 +1067,12 @@ mod tests { assert!(!v.iter().any_(|&x| x > 100)); assert!(!v.slice(0, 0).iter().any_(|_| fail!())); } + + #[test] + fn test_find() { + let v = &[1, 3, 9, 27, 103, 14, 11]; + assert_eq!(*v.iter().find(|x| *x & 1 == 0).unwrap(), 14); + assert_eq!(*v.iter().find(|x| *x % 3 == 0).unwrap(), 3); + assert!(v.iter().find(|x| *x % 12 == 0).is_none()); + } } |
