rust-itertools / itertools

Extra iterator adaptors, iterator methods, free functions, and macros.
https://docs.rs/itertools/
Apache License 2.0
2.72k stars 309 forks source link

.collect_tuple_or_default suggestion #812

Closed asibahi closed 10 months ago

asibahi commented 10 months ago

Hello everyone.

I am curious about the feasibility of a function, implemented for T : Default, where you if you collect an iterator into a tuple, and there are less elements than the length of the tuple, the other items are instead replaced with 0.

So for example if my iterator is vec![ 5 ] and I collect into a ( usize, usize ) tuple, I end up with a ( 5, 0 ). In understand the inverse of trimming to tuple length is covered with .next_tuple() but this is a suggestion into the other end.

If you guys feel it is something that is worth adding I can try adding it to the library, although I do not quite understand Traits and Macros (yet?) and I might muck things up a bit.

phimuemue commented 10 months ago

Would vec![5].into_iter().chain(std::iter::repeat(Default::default())).next_tuple().unwrap() be ok for your use case? It's probably slighly less efficient than a bespoke function, but I'm unsure the new function would be widely used.

Alternatively, pad_using might help.

Philippe-Cholet commented 10 months ago

I'm not sure we should expand much on "tuple" methods as we might use in a "near future" array methods instead? (c.f. const generics) I don't remember seeing a discussion on tuple methods vs const generic array methods (like deprecate tuple versions for array versions?! I'm not looking for a big discussion here).

asibahi commented 10 months ago

Would vec![5].into_iter().chain(std::iter::repeat(Default::default())).next_tuple().unwrap() be ok for your use case? It's probably slighly less efficient than a bespoke function, but I'm unsure the new function would be widely used.

Alternatively, pad_using might help.

oh I didnt know about pad_using. I think this exactly covers it. Thank you.

Philippe-Cholet commented 10 months ago

Feel free to re-open it if you want.