`reduce_with` for Iterators

When working out one value from an iterator, you only have fold, which needs an start value and reduce, which uses the first value as a start value. But there is no way of using the start value, mapping just that to another type and working with the other values normally. For that, I propose reduce_with, which would look something like this:

fn reduce_with<B, F, I>(mut self, init: I, f: F) -> Option<B>
where
    Self: Sized,
    I: FnOnce(Self::Item) -> B,
    F: FnMut(B, Self::Item) -> B,
{
    let first = init(self.next()?);
    Some(self.fold(first, f))
}

Thoughts?

5 Likes

i've often wanted something like this!

I am unsure if I can just PR that in the std, maybe there are more places where I need to change something to fully be in a Iterator. I thought I saw some code which forwarded some function impls to other functions, but I can't find it.. So do I need some sort of sign off here or can this just be PRed and discussed there?

You should file an ACP: Feature lifecycle - Standard library developers Guide

1 Like

It's essentially the same as this ACP, just under a different name:

1 Like

For Iterator APIs in particular, itertools might be willing to add features that the standard library declined.

2 Likes