@@ -190,9 +190,7 @@ pub trait Iterator {
190
190
#[ inline]
191
191
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
192
192
fn last ( self ) -> Option < Self :: Item > where Self : Sized {
193
- let mut last = None ;
194
- for x in self { last = Some ( x) ; }
195
- last
193
+ self . fold ( None , |_, x| Some ( x) )
196
194
}
197
195
198
196
/// Consumes the `n` first elements of the iterator, then returns the
@@ -1228,13 +1226,14 @@ pub trait Iterator {
1228
1226
let mut left: B = Default :: default ( ) ;
1229
1227
let mut right: B = Default :: default ( ) ;
1230
1228
1231
- for x in self {
1229
+ // Use fold to enable iterator-specific implementations.
1230
+ self . fold ( ( ) , |_, x| {
1232
1231
if f ( & x) {
1233
- left. extend ( Some ( x) )
1232
+ left. extend ( Some ( x) ) ;
1234
1233
} else {
1235
- right. extend ( Some ( x) )
1234
+ right. extend ( Some ( x) ) ;
1236
1235
}
1237
- }
1236
+ } ) ;
1238
1237
1239
1238
( left, right)
1240
1239
}
@@ -1794,10 +1793,10 @@ pub trait Iterator {
1794
1793
let mut ts: FromA = Default :: default ( ) ;
1795
1794
let mut us: FromB = Default :: default ( ) ;
1796
1795
1797
- for ( t, u) in self {
1796
+ self . fold ( ( ) , |_ , ( t, u) | {
1798
1797
ts. extend ( Some ( t) ) ;
1799
1798
us. extend ( Some ( u) ) ;
1800
- }
1799
+ } ) ;
1801
1800
1802
1801
( ts, us)
1803
1802
}
@@ -2116,7 +2115,7 @@ pub trait Iterator {
2116
2115
/// commonalities of {max,min}{,_by}. In particular, this avoids
2117
2116
/// having to implement optimizations several times.
2118
2117
#[ inline]
2119
- fn select_fold1 < I , B , FProj , FCmp > ( mut it : I ,
2118
+ fn select_fold1 < I , B , FProj , FCmp > ( it : I ,
2120
2119
mut f_proj : FProj ,
2121
2120
mut f_cmp : FCmp ) -> Option < ( B , I :: Item ) >
2122
2121
where I : Iterator ,
@@ -2126,17 +2125,15 @@ fn select_fold1<I,B, FProj, FCmp>(mut it: I,
2126
2125
// start with the first element as our selection. This avoids
2127
2126
// having to use `Option`s inside the loop, translating to a
2128
2127
// sizeable performance gain (6x in one case).
2129
- it. next ( ) . map ( |mut sel| {
2130
- let mut sel_p = f_proj ( & sel) ;
2131
-
2132
- for x in it {
2133
- let x_p = f_proj ( & x) ;
2134
- if f_cmp ( & sel_p, & sel, & x_p, & x) {
2135
- sel = x;
2136
- sel_p = x_p;
2128
+ let mut projected = it. map ( |x| ( f_proj ( & x) , x) ) ;
2129
+ projected. next ( ) . map ( |( sel_p, sel) | {
2130
+ projected. fold ( ( sel_p, sel) , |( sel_p, sel) , ( x_p, x) | {
2131
+ if f_cmp ( & sel_p, & sel, & x_p, & x) {
2132
+ ( x_p, x)
2133
+ } else {
2134
+ ( sel_p, sel)
2137
2135
}
2138
- }
2139
- ( sel_p, sel)
2136
+ } )
2140
2137
} )
2141
2138
}
2142
2139
0 commit comments