@@ -2005,6 +2005,44 @@ 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
+ /// fn find_max<I>(iter: I) -> Option<I::Item>
2019
+ /// where I: Iterator,
2020
+ /// I::Item: Ord,
2021
+ /// {
2022
+ /// iter.fold_first(|a, b| {
2023
+ /// a.partial_cmp(b).map(move |cmp| match cmp {
2024
+ /// Ordering::Greater | Ordering::Equal => a,
2025
+ /// Ordering::Less => b,
2026
+ /// })
2027
+ /// })
2028
+ /// }
2029
+ /// let a = [10, 20, 5, -23, 0];
2030
+ /// let b = [];
2031
+ ///
2032
+ /// assert_eq!(find_max(a.iter()), Some(20));
2033
+ /// assert_eq!(find_max(b.iter()), None);
2034
+ /// ```
2035
+ #[ inline]
2036
+ #[ unstable( feature = "iterator_fold_self" , issue = "68125" ) ]
2037
+ fn fold_first < F > ( mut self , f : F ) -> Option < Self :: Item >
2038
+ where
2039
+ Self : Sized ,
2040
+ F : FnMut ( Self :: Item , Self :: Item ) -> Self :: Item ,
2041
+ {
2042
+ let first = self . next ( ) ?;
2043
+ Some ( self . fold ( first, f) )
2044
+ }
2045
+
2008
2046
/// Tests if every element of the iterator matches a predicate.
2009
2047
///
2010
2048
/// `all()` takes a closure that returns `true` or `false`. It applies
@@ -2497,7 +2535,7 @@ pub trait Iterator {
2497
2535
move |x, y| cmp:: max_by ( x, y, & mut compare)
2498
2536
}
2499
2537
2500
- fold1 ( self , fold ( compare) )
2538
+ self . fold_first ( fold ( compare) )
2501
2539
}
2502
2540
2503
2541
/// Returns the element that gives the minimum value from the
@@ -2561,7 +2599,7 @@ pub trait Iterator {
2561
2599
move |x, y| cmp:: min_by ( x, y, & mut compare)
2562
2600
}
2563
2601
2564
- fold1 ( self , fold ( compare) )
2602
+ self . fold_first ( fold ( compare) )
2565
2603
}
2566
2604
2567
2605
/// Reverses an iterator's direction.
@@ -3214,20 +3252,6 @@ pub trait Iterator {
3214
3252
}
3215
3253
}
3216
3254
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
3255
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
3232
3256
impl < I : Iterator + ?Sized > Iterator for & mut I {
3233
3257
type Item = I :: Item ;
0 commit comments