-
Notifications
You must be signed in to change notification settings - Fork 309
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Implement peeking_fold_while #400
base: master
Are you sure you want to change the base?
Conversation
This is an interesting idea, and maybe I am missing something, but I suspected that
This has the advantage that it works for any Could you shed some light on the advantages of |
I actually hadn't thought of your solution and its existence probably eliminates a lot of use cases of // <----> <-----> <---->
let a = [20, 30, 100, 10, 40, 50];
let mut it = a.iter().peekable();
let sum = it.peeking_fold_while(0i8, |acc, &&x| acc.checked_add(x).ok_or(acc));
assert_eq!(sum, Err(50));
let sum = it.peeking_fold_while(0i8, |acc, &&x| acc.checked_add(x).ok_or(acc));
assert_eq!(sum, Err(110));
let sum = it.peeking_fold_while(0i8, |acc, &&x| acc.checked_add(x).ok_or(acc));
assert_eq!(sum, Ok(90)); whereas using |
Thank you for your elaboration. I agree, we should see if it's worth to include it in the crate. As a sidenote: The use case you gave reminded me of something like |
Given that there is precedence with |
From #979 (comment) On point |
Issue
try_fold
is capable of folding an iterator until a short-circuiting condition is met. For instance, the short-circuiting example in the docs sums up integers until an integer overflow is encountered. However,try_fold
ends up consuming the element that caused the short-circuit (in this case, the element 100).Solution
I've implemented a
PeekingFoldWhile
trait forPeekable
s andPutBack
s with a methodpeeking_fold_while
that does not consume the short-circuiting element. Using it on the above example leads to the following behavior:This is my first attempt at contributing so feedback is welcome 😄