@@ -308,6 +308,9 @@ pub trait IteratorUtil<A> {
308308 /// assert!(!it.any_(|&x| *x == 3));
309309 /// ~~~
310310 fn any_ ( & mut self , f : & fn ( A ) -> bool ) -> bool ;
311+
312+ /// Return the first element satisfying the specified predicate
313+ fn find ( & mut self , predicate : & fn ( & A ) -> bool ) -> Option < A > ;
311314}
312315
313316/// 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 {
421424 None => { break ; }
422425 }
423426 }
424- return accum;
427+ accum
425428 }
426429
427430 /// Count the number of items yielded by an iterator
@@ -431,13 +434,22 @@ impl<A, T: Iterator<A>> IteratorUtil<A> for T {
431434 #[ inline( always) ]
432435 fn all ( & mut self , f : & fn ( A ) -> bool ) -> bool {
433436 for self . advance |x| { if !f ( x) { return false ; } }
434- return true ;
437+ true
435438 }
436439
437440 #[ inline( always) ]
438441 fn any_ ( & mut self , f : & fn ( A ) -> bool ) -> bool {
439442 for self . advance |x| { if f ( x) { return true ; } }
440- return false ;
443+ false
444+ }
445+
446+ /// Return the first element satisfying the specified predicate
447+ #[ inline( always) ]
448+ fn find ( & mut self , predicate : & fn ( & A ) -> bool ) -> Option < A > {
449+ for self . advance |x| {
450+ if predicate ( & x) { return Some ( x) }
451+ }
452+ None
441453 }
442454}
443455
@@ -1055,4 +1067,12 @@ mod tests {
10551067 assert ! ( !v. iter( ) . any_( |& x| x > 100 ) ) ;
10561068 assert ! ( !v. slice( 0 , 0 ) . iter( ) . any_( |_| fail!( ) ) ) ;
10571069 }
1070+
1071+ #[ test]
1072+ fn test_find( ) {
1073+ let v = & [ 1 , 3 , 9 , 27 , 103 , 14 , 11 ] ;
1074+ assert_eq ! ( * v. iter( ) . find( |x| * x & 1 == 0 ) . unwrap( ) , 14 ) ;
1075+ assert_eq ! ( * v. iter( ) . find( |x| * x % 3 == 0 ) . unwrap( ) , 3 ) ;
1076+ assert ! ( v. iter( ) . find( |x| * x % 12 == 0 ) . is_none( ) ) ;
1077+ }
10581078}
0 commit comments