-
Notifications
You must be signed in to change notification settings - Fork 20
fold_first API Change Proposal #157
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
Comments
That example exists in the docs mostly to emphasize the order in which the accumulator is applied. Can you put more about your real-life situations where this is something you need? My instinct is that we might not want another of these consumers, especially with a called-at-most-once closure. |
The next-then-fold pattern feels like a more general tap-like thing where you have a pile of adapter calls, then want to apply something to that temporary and then want to apply something else. |
I recently wrote some code that would have benefited from this API (and I'm pretty sure I've looked for it in the past too): let mut messages = messages.into_iter();
let initial = Error::msg(messages.next().ok_or_else(|| eyre!("missing initial message"))?);
messages.fold(initial, |err, msg| err.wrap_err(msg)) with messages
.into_iter()
.fold_first(Error::msg, |err, msg| acc.wrap_err(msg))
.ok_or_else(|| eyre!("missing initial message"))? (code context: |
We discussed this briefly during this week's libs-api meeting. There weren't many strong opinions, but nobody wanted to second this addition, so we're going to close it. The recommendation is to call |
Proposal
Problem statement
Iterator::fold
is an extremely useful API to process all the elements in an iterator.Sometimes you don't have a sensible initial value. This is where
Iterator::reduce
comes in.However, this removes some flexibility with the return type. It must be the same as the item stream.
There's a middle ground where you instead derive the initial fold value with the first element in the iterator.
Motivation, use-cases
The docs for
fold
presents this exampleThere's no way to avoid the
(0 + 1)
situation with eitherfold
orreduce
unless you fold over aOption<String>
or reduce overString
iterators.With
fold_first
, this is easySolution sketches
rust-lang/rust#106348
Links and related work
What happens now?
This issue is part of the libs-api team API change proposal process. Once this issue is filed the libs-api team will review open proposals in its weekly meeting. You should receive feedback within a week or two.
The text was updated successfully, but these errors were encountered: