@@ -308,6 +308,12 @@ 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 > ;
314
+
315
+ /// Return the index of the first element satisfying the specified predicate
316
+ fn position_ ( & mut self , predicate : & fn ( A ) -> bool ) -> Option < uint > ;
311
317
}
312
318
313
319
/// Iterator adaptors provided for every `Iterator` implementation. The adaptor objects are also
@@ -421,7 +427,7 @@ impl<A, T: Iterator<A>> IteratorUtil<A> for T {
421
427
None => { break ; }
422
428
}
423
429
}
424
- return accum;
430
+ accum
425
431
}
426
432
427
433
/// Count the number of items yielded by an iterator
@@ -431,13 +437,35 @@ impl<A, T: Iterator<A>> IteratorUtil<A> for T {
431
437
#[ inline( always) ]
432
438
fn all ( & mut self , f : & fn ( A ) -> bool ) -> bool {
433
439
for self . advance |x| { if !f ( x) { return false ; } }
434
- return true ;
440
+ true
435
441
}
436
442
437
443
#[ inline( always) ]
438
444
fn any_ ( & mut self , f : & fn ( A ) -> bool ) -> bool {
439
445
for self . advance |x| { if f ( x) { return true ; } }
440
- return false ;
446
+ false
447
+ }
448
+
449
+ /// Return the first element satisfying the specified predicate
450
+ #[ inline( always) ]
451
+ fn find_ ( & mut self , predicate : & fn ( & A ) -> bool ) -> Option < A > {
452
+ for self . advance |x| {
453
+ if predicate ( & x) { return Some ( x) }
454
+ }
455
+ None
456
+ }
457
+
458
+ /// Return the index of the first element satisfying the specified predicate
459
+ #[ inline]
460
+ fn position_ ( & mut self , predicate : & fn ( A ) -> bool ) -> Option < uint > {
461
+ let mut i = 0 ;
462
+ for self . advance |x| {
463
+ if predicate ( x) {
464
+ return Some ( i) ;
465
+ }
466
+ i += 1 ;
467
+ }
468
+ None
441
469
}
442
470
}
443
471
@@ -1055,4 +1083,20 @@ mod tests {
1055
1083
assert ! ( !v. iter( ) . any_( |& x| x > 100 ) ) ;
1056
1084
assert ! ( !v. slice( 0 , 0 ) . iter( ) . any_( |_| fail!( ) ) ) ;
1057
1085
}
1086
+
1087
+ #[ test]
1088
+ fn test_find( ) {
1089
+ let v = & [ 1 , 3 , 9 , 27 , 103 , 14 , 11 ] ;
1090
+ assert_eq ! ( * v. iter( ) . find_( |x| * x & 1 == 0 ) . unwrap( ) , 14 ) ;
1091
+ assert_eq ! ( * v. iter( ) . find_( |x| * x % 3 == 0 ) . unwrap( ) , 3 ) ;
1092
+ assert ! ( v. iter( ) . find_( |x| * x % 12 == 0 ) . is_none( ) ) ;
1093
+ }
1094
+
1095
+ #[ test]
1096
+ fn test_position( ) {
1097
+ let v = & [ 1 , 3 , 9 , 27 , 103 , 14 , 11 ] ;
1098
+ assert_eq ! ( v. iter( ) . position_( |x| * x & 1 == 0 ) . unwrap( ) , 5 ) ;
1099
+ assert_eq ! ( v. iter( ) . position_( |x| * x % 3 == 0 ) . unwrap( ) , 1 ) ;
1100
+ assert ! ( v. iter( ) . position_( |x| * x % 12 == 0 ) . is_none( ) ) ;
1101
+ }
1058
1102
}
0 commit comments