itertools icon indicating copy to clipboard operation
itertools copied to clipboard

Product and MultiProduct should implement ExactSizeIterator if all the constituent iterators implement it

Open sunshowers opened this issue 4 years ago • 6 comments

Thanks for itertools! It's super useful :)

I do have one feature request: I love the Cartesian product iterators because they were just what I wanted for a use case, but I noticed that they're missing ExactSizeIterator implementations. I think the trait can be implemented if all the constituent iterators implement the trait.

I'd expect the result to be the product of the lengths of all the constituent iterators.

I'd be happy to submit a PR for this some time in the next couple of weeks if no one else gets to it. Thanks!

sunshowers avatar Dec 23 '20 03:12 sunshowers

Because of the potential for overflow, it's not actually correct to implement ExactSizeIterator for any adapter that makes an iterator longer -- you'll notice that Chain doesn't implement it either.

scottmcm avatar Dec 23 '20 05:12 scottmcm

Ah, good point. Could the TrustedLen contract be followed (or is it already followed)? https://doc.rust-lang.org/stable/std/iter/trait.TrustedLen.html

sunshowers avatar Dec 23 '20 06:12 sunshowers

That trait is unstable, so even if the contract could be followed, the trait itself can't be implemented

SkiFire13 avatar Dec 27 '20 19:12 SkiFire13

(yeah that's what I meant, just following the contract and documenting that it is followed)

sunshowers avatar Dec 27 '20 21:12 sunshowers

Product already overrides size_hint, and so does MultiProduct. Is this sufficient?

jswrenn avatar Dec 27 '20 22:12 jswrenn

It does, yes! So it looks like the only thing to do is to verify that the impla follow the TrustedLen contract, update them if they don't, and document that they do.

Rain (they/she)

On Sun, Dec 27, 2020, 14:24 Jack Wrenn [email protected] wrote:

Product already overrides size_hint https://docs.rs/itertools/0.10.0/src/itertools/adaptors/mod.rs.html#330-339, and so does MultiProduct https://docs.rs/itertools/0.10.0/src/itertools/adaptors/multi_product.rs.html#186-206 .

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/rust-itertools/itertools/issues/509#issuecomment-751523048, or unsubscribe https://github.com/notifications/unsubscribe-auth/AABMDCQUSHHAW3QSLAFMKSTSW6XZPANCNFSM4VGN664Q .

sunshowers avatar Dec 28 '20 00:12 sunshowers