Sum the positive amounts and count the negative ones in one pass with fold
Write summarize, which takes a slice of signed amounts and returns a pair: the total of the positive amounts and the number of the negative ones.
Requirements:
- One pass over the slice, with no
for/whileloop and no temporaryVec. - Zero counts as neither positive nor negative.
[120, -40, 0, 75, -5]gives(195, 2); an empty slice gives(0, 0).
fn summarize(amounts: &[i64]) -> (i64, usize) {
// your code here
}Write the implementation.
Do not add extra use lines unless the task says so explicitly.
Fold into a tuple: amounts.iter().fold((0, 0), |(total, neg), &a| …), adding a to total if a > 0 and 1 to neg if a < 0. One pass, no buffer; two filter chains read the slice twice, and partition allocates two Vecs.
- Counting two
filterchains as one pass, though each reads the whole slice again - Using
partitionand counting the secondVec, where the zeros land as well - Reaching for
reduce, whose accumulator must have the element type, not a tuple
- How would
try_foldstop the pass as soon as the total overflowsi64? - When is a plain
forloop clearer thanfoldfor the same task?
fold takes the initial accumulator and a closure that turns the accumulator and the next element into a new accumulator. Here the accumulator is a tuple, and the patterns in the closure's parameters take it apart at once: (total, negatives) are the two halves of the tuple, and &a strips the reference to give an i64 by value.
fn summarize(amounts: &[i64]) -> (i64, usize) {
amounts.iter().fold((0, 0), |(total, negatives), &a| {
if a > 0 {
(total + a, negatives)
} else if a < 0 {
(total, negatives + 1)
} else {
(total, negatives) // zero changes neither the total nor the count
}
})
}
fn main() {
println!("{:?}", summarize(&[120, -40, 0, 75, -5])); // (195, 2)
println!("{:?}", summarize(&[])); // (0, 0)
}An empty slice needs no special case: fold simply returns the initial (0, 0). The alternatives lose. Two chains, filter(...).sum() and filter(...).count(), give the same answer but read the slice twice. partition allocates two Vecs, and zero lands in the second part, so for the example the second part has length 3, not 2. reduce does not fit: its accumulator has the element type, while this task needs a tuple. If the total may overflow i64, the same pass is written with try_fold and checked_add, which stops at the first overflow and returns None.