So a pretty standard pattern in imperative programming is to create some mutable state (like sum), then iterate over some values, check a predicate, and if the predicate fails, break the for-loop.
the functional tool, fold
does something similar, but I can't break out of the iterator. I can instead use something like take_while
, but that's the best I can think of.
Is that my best shot here?
fn main() {
// some vector of maybe bad overflow stuff
let p: Vec<u128> = vec![0, 1, 2, 3, 4];
let mut is_overflow = false;
let sum: u128 = p.iter().fold(0, |acc, &amt| {
match u128::checked_add(acc, amt) {
None => {
is_overflow = true;
0
//break; // can't!
}
Some(x) => x,
}
});
dbg!(sum);
let mut sum = 0;
let mut is_overflow = false;
let _: Vec<_> = p
.into_iter()
.take_while(|&amt| match u128::checked_add(sum, amt) {
Some(x) => {
sum = x;
true
}
None => {
is_overflow = true;
false
}
})
.collect();
dbg!(sum);
}