Idiomatic way to create alternating stream

I want to provide the user of the library with the stream (not in the async sense (yet), but as a generalization of iterator) yielding alternating items - something like "start1-end1-start2-end2-...". Of course, I can forget about alternation and just provide an iterator of Eithers, but is there any idiomatic way to enforce the alternation on type level while still providing ergonomic interface?

You could create an iterator adapter over a DoubleEndedIterator that contains a flag, denoting whether you want the next item from the front or from the end, and the next() method would check and flip that flag.

Here's a quick playground demo.

2 Likes

The code seems too big/verbose for such trivial(?) task. Is it possible to cut down on it?

You could just inline the logic at the use site. Still, extracting it to a separate type facilitates reading and reuse, so it's generally considered better style.