@@ -308,6 +308,9 @@ pub trait IteratorUtil<A> {
308
308
/// assert!(!it.any_(|&x| *x == 3));
309
309
/// ~~~
310
310
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 > ;
311
314
}
312
315
313
316
/// 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 {
421
424
None => { break ; }
422
425
}
423
426
}
424
- return accum;
427
+ accum
425
428
}
426
429
427
430
/// Count the number of items yielded by an iterator
@@ -431,13 +434,22 @@ impl<A, T: Iterator<A>> IteratorUtil<A> for T {
431
434
#[ inline( always) ]
432
435
fn all ( & mut self , f : & fn ( A ) -> bool ) -> bool {
433
436
for self . advance |x| { if !f ( x) { return false ; } }
434
- return true ;
437
+ true
435
438
}
436
439
437
440
#[ inline( always) ]
438
441
fn any_ ( & mut self , f : & fn ( A ) -> bool ) -> bool {
439
442
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
441
453
}
442
454
}
443
455
@@ -1055,4 +1067,12 @@ mod tests {
1055
1067
assert ! ( !v. iter( ) . any_( |& x| x > 100 ) ) ;
1056
1068
assert ! ( !v. slice( 0 , 0 ) . iter( ) . any_( |_| fail!( ) ) ) ;
1057
1069
}
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
+ }
1058
1078
}
0 commit comments