Is there an itertools fn for this?

Sure, here's this one (still restricted to slices).

This would require some careful documentation though... it calls the function on some items more than once. This could be avoided by storing an Option<usize> to indicate the value of the overflow item with enough care. OK, that wasn't too hard either. I'll leave the other version too in case it's helpful to see the progression from the less generic version onward.

Can we generalize to any iterator over T

It's easy to return subslices from a slice, but for an arbitrary iterator, we're going to have to store the dynamically sized (dynamic number of returned values per iteration) somewhere. Your OP used Vecs anyway, so probably this is acceptable to you.

Here's a version for that. In this one I did take care to only call the closure on each item once from the start; it was actually more natural here as we just call the closure as we consume the inner iterator.

Now that I've done it, just looking at what I called it -- collect_by_sum -- this could be generalized even further to return arbitrary collections ala collect, at the cost of inference. But I'll stop here.

Let me know if you want me to walk through anything in more detail.

1 Like