Stop fold at first None when iterator yield

This commit is contained in:
Mara Bos 2021-01-19 12:17:58 +00:00 committed by Lzu Tao
parent 20d8478864
commit 9272d53c5a
2 changed files with 14 additions and 0 deletions

View File

@ -176,6 +176,8 @@ where
if !needs_sep {
if let Some(x) = iter.next() {
accum = f(accum, x);
} else {
return accum;
}
}

View File

@ -3577,6 +3577,18 @@ fn test_intersperse_fold() {
acc
});
assert_eq!(v.as_slice(), [9, 2, 9, 3]);
struct NoneAtStart(i32); // Produces: None, Some(2), Some(3), None, ...
impl Iterator for NoneAtStart {
type Item = i32;
fn next(&mut self) -> Option<i32> {
self.0 += 1;
Some(self.0).filter(|i| i % 3 != 1)
}
}
let v = NoneAtStart(0).intersperse(1000).fold(0, |a, b| a + b);
assert_eq!(v, 0);
}
#[test]