Skip to content

Commit 8852bf2

Browse files
committed
Replace more Iterator for-loops with fold.
1 parent f095f0d commit 8852bf2

File tree

1 file changed

+17
-20
lines changed

1 file changed

+17
-20
lines changed

src/libcore/iter/iterator.rs

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -190,9 +190,7 @@ pub trait Iterator {
190190
#[inline]
191191
#[stable(feature = "rust1", since = "1.0.0")]
192192
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))
196194
}
197195

198196
/// Consumes the `n` first elements of the iterator, then returns the
@@ -1228,13 +1226,14 @@ pub trait Iterator {
12281226
let mut left: B = Default::default();
12291227
let mut right: B = Default::default();
12301228

1231-
for x in self {
1229+
// Use fold to enable iterator-specific implementations.
1230+
self.fold((), |_, x| {
12321231
if f(&x) {
1233-
left.extend(Some(x))
1232+
left.extend(Some(x));
12341233
} else {
1235-
right.extend(Some(x))
1234+
right.extend(Some(x));
12361235
}
1237-
}
1236+
});
12381237

12391238
(left, right)
12401239
}
@@ -1794,10 +1793,10 @@ pub trait Iterator {
17941793
let mut ts: FromA = Default::default();
17951794
let mut us: FromB = Default::default();
17961795

1797-
for (t, u) in self {
1796+
self.fold((), |_, (t, u)| {
17981797
ts.extend(Some(t));
17991798
us.extend(Some(u));
1800-
}
1799+
});
18011800

18021801
(ts, us)
18031802
}
@@ -2116,7 +2115,7 @@ pub trait Iterator {
21162115
/// commonalities of {max,min}{,_by}. In particular, this avoids
21172116
/// having to implement optimizations several times.
21182117
#[inline]
2119-
fn select_fold1<I,B, FProj, FCmp>(mut it: I,
2118+
fn select_fold1<I,B, FProj, FCmp>(it: I,
21202119
mut f_proj: FProj,
21212120
mut f_cmp: FCmp) -> Option<(B, I::Item)>
21222121
where I: Iterator,
@@ -2126,17 +2125,15 @@ fn select_fold1<I,B, FProj, FCmp>(mut it: I,
21262125
// start with the first element as our selection. This avoids
21272126
// having to use `Option`s inside the loop, translating to a
21282127
// 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)
21372135
}
2138-
}
2139-
(sel_p, sel)
2136+
})
21402137
})
21412138
}
21422139

0 commit comments

Comments
 (0)