refactor: Replace fold with try_fold
The and_then combinator performs a kind of bitwise and operation on two Option types here. This is useful since the `checked` arithmetic returns an option thereby accumulating Option types. Therefore, either the checked arithmetic operation performs the addition of the unwrapped accumulator, or it returns None. Instead of using `and_then` use the provided `try_fold` method which will short circuit on `None` when the checked arithmetic is used. Also, simplify the staring condition using `Amount:ZERO` since this is logically equivalent to using the first value if one exists. Lastly, by using the built in `try_fold`, it's possible the performance will be improved by making use of the short circuit ability instead of evaluating each item even when the accumulator holds a None type.
This commit is contained in:
parent
7c51612136
commit
812c21e2e4
|
@ -605,9 +605,7 @@ where
|
|||
T: Iterator<Item = Amount>,
|
||||
{
|
||||
fn checked_sum(mut self) -> Option<Amount> {
|
||||
let first = Some(self.next().unwrap_or_default());
|
||||
|
||||
self.fold(first, |acc, item| acc.and_then(|acc| acc.checked_add(item)))
|
||||
self.try_fold(Amount::ZERO, Amount::checked_add)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -616,9 +614,7 @@ where
|
|||
T: Iterator<Item = SignedAmount>,
|
||||
{
|
||||
fn checked_sum(mut self) -> Option<SignedAmount> {
|
||||
let first = Some(self.next().unwrap_or_default());
|
||||
|
||||
self.fold(first, |acc, item| acc.and_then(|acc| acc.checked_add(item)))
|
||||
self.try_fold(SignedAmount::ZERO, SignedAmount::checked_add)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue