Logo

Programming-Idioms

  • Ruby
  • Go

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.

import "fmt"
for i := range min(len(items1), len(items2)) {
	fmt.Println(items1[i])
	fmt.Println(items2[i])

}
for i := 0; i < len(items1) || i < len(items2); i++ {
	if i < len(items1) {
		fmt.Println(items1[i])
	}
	if i < len(items2) {
		fmt.Println(items2[i])
	}
}
items1.zip(items2){|pair| puts pair}

There will be as much pairs as there are items in items1. items2 will be "padded" with nils or trimmed as needed.
(doseq [i (interleave items1 items2)]
  (println i))

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

New implementation...