rust-itertools / itertools

Extra iterator adaptors, iterator methods, free functions, and macros.
https://docs.rs/itertools/
Apache License 2.0
2.72k stars 309 forks source link

Use `try_fold` instead of `fold(Some(...), )` #746

Closed Philippe-Cholet closed 1 year ago

Philippe-Cholet commented 1 year ago

I used .fold(Some(...), ...) pattern three times because it was used in permutations.rs (where I started a series of changes) but it leads to a lot of unnecessary .and_then if we have None early. I previously thought it could be better replaced by something like .map(...).sum::<Option<_>>() with MSRV 1.37+ but no because it does not prevent the underlying operation to overflow. And there is no checked_sum/checked_product. Related to #745 After looking at Itertools::fold_while, I found out that Iterator::try_fold is the right method for the job.

PS: I was gonna suggest to deprecate Itertools::fold_while in favor of Iterator::try_fold but I see there was quite some discussion about this in #469. Not sure to understand the whole thing though.