Logo

Programming-Idioms

  • D
  • Smalltalk

Idiom #143 Iterate alternatively over two lists

Iterate alternatively over the elements of the lists items1 and items2. For each iteration, print the element.

Explain what happens if items1 and items2 have different size.

items1 with: items2 do: [:item1 :item2 |
  Transcript 
	showln: item1;
	showln: item2].

If the collections have different size, this will raise an exception before the iteration starts.
stream1 := items1 readStream.
stream2 := items2 readStream.
[stream1 atEnd ifFalse: [Transcript showln: stream1 next].
 stream2 atEnd ifFalse: [Transcript showln: stream2 next]]
	doWhileFalse: [stream1 atEnd or: [stream2 atEnd]].
import std.range;
import std.algorithm.iteration;
import std.stdio;
roundRobin(items1, items2).each!writeln;
(doseq [i (interleave items1 items2)]
  (println i))

interleave can receive any number of items, but truncates when any of them is exhausted

New implementation...