rust-itertools / itertools

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

chain_with for lazy second iterator construction #370

Open Ten0 opened 5 years ago

Ten0 commented 5 years ago

It might be useful to add a chain_with function to the itertools that does the same thing as chain but lazily calling the function that builds the iterator.

This would make chaining with iterators computed in another thread easier.

The workaround described here is somewhat limited because map is not an FnOnce even though the way it is used provides the guarantee it will only be used once.

Ten0 commented 5 years ago

This is pretty much .chain(std::iter::once_with(|| ...).flatten()), but more efficient (esp. since it could specialize size_hint and the like). https://doc.rust-lang.org/std/iter/fn.once_with.html

bb010g commented 3 years ago

Ran into this pattern while chaining an OnceCell<impl Iterator>; using Iterator::chain caused evaluation to happen too early.

Philippe-Cholet commented 8 months ago

I think it has some value and I see it received some likes. I thought I would do it myself but other parts of itertools took my attention so help wanted.

phimuemue commented 8 months ago

I'm unsure if this is really tied to Chain (what about a lazy Interleave?) - or even to Iterator (what about other things that should be evaluated lazily). (See here for a weak attempt of a generic lazy thing.)

Philippe-Cholet commented 8 months ago

True, I'm now unsure this should be done. Your attempt of a generic lazy thing interest me related to my https://github.com/rust-itertools/itertools/issues/791#issuecomment-1822364744.