@@ -2005,6 +2005,43 @@ pub trait Iterator {
2005
2005
self . try_fold ( init, ok ( f) ) . unwrap ( )
2006
2006
}
2007
2007
2008
+ /// The same as [`fold()`](#method.fold), but uses the first element in the
2009
+ /// iterator as the initial value, folding every subsequent element into it.
2010
+ /// If the iterator is empty, return `None`; otherwise, return the result
2011
+ /// of the fold.
2012
+ ///
2013
+ /// # Example
2014
+ ///
2015
+ /// Find the maximum value:
2016
+ ///
2017
+ /// ```
2018
+ /// #![feature(iterator_fold_self)]
2019
+ ///
2020
+ /// fn find_max<I>(iter: I) -> Option<I::Item>
2021
+ /// where I: Iterator,
2022
+ /// I::Item: Ord,
2023
+ /// {
2024
+ /// iter.fold_first(|a, b| {
2025
+ /// if a >= b { a } else { b }
2026
+ /// })
2027
+ /// }
2028
+ /// let a = [10, 20, 5, -23, 0];
2029
+ /// let b: [u32; 0] = [];
2030
+ ///
2031
+ /// assert_eq!(find_max(a.iter()), Some(&20));
2032
+ /// assert_eq!(find_max(b.iter()), None);
2033
+ /// ```
2034
+ #[ inline]
2035
+ #[ unstable( feature = "iterator_fold_self" , issue = "68125" ) ]
2036
+ fn fold_first < F > ( mut self , f : F ) -> Option < Self :: Item >
2037
+ where
2038
+ Self : Sized ,
2039
+ F : FnMut ( Self :: Item , Self :: Item ) -> Self :: Item ,
2040
+ {
2041
+ let first = self . next ( ) ?;
2042
+ Some ( self . fold ( first, f) )
2043
+ }
2044
+
2008
2045
/// Tests if every element of the iterator matches a predicate.
2009
2046
///
2010
2047
/// `all()` takes a closure that returns `true` or `false`. It applies
@@ -2497,7 +2534,7 @@ pub trait Iterator {
2497
2534
move |x, y| cmp:: max_by ( x, y, & mut compare)
2498
2535
}
2499
2536
2500
- fold1 ( self , fold ( compare) )
2537
+ self . fold_first ( fold ( compare) )
2501
2538
}
2502
2539
2503
2540
/// Returns the element that gives the minimum value from the
@@ -2561,7 +2598,7 @@ pub trait Iterator {
2561
2598
move |x, y| cmp:: min_by ( x, y, & mut compare)
2562
2599
}
2563
2600
2564
- fold1 ( self , fold ( compare) )
2601
+ self . fold_first ( fold ( compare) )
2565
2602
}
2566
2603
2567
2604
/// Reverses an iterator's direction.
@@ -3214,20 +3251,6 @@ pub trait Iterator {
3214
3251
}
3215
3252
}
3216
3253
3217
- /// Fold an iterator without having to provide an initial value.
3218
- #[ inline]
3219
- fn fold1 < I , F > ( mut it : I , f : F ) -> Option < I :: Item >
3220
- where
3221
- I : Iterator ,
3222
- F : FnMut ( I :: Item , I :: Item ) -> I :: Item ,
3223
- {
3224
- // start with the first element as our selection. This avoids
3225
- // having to use `Option`s inside the loop, translating to a
3226
- // sizeable performance gain (6x in one case).
3227
- let first = it. next ( ) ?;
3228
- Some ( it. fold ( first, f) )
3229
- }
3230
-
3231
3254
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
3232
3255
impl < I : Iterator + ?Sized > Iterator for & mut I {
3233
3256
type Item = I :: Item ;
0 commit comments