interleave

fun <A> Iterable<A>.interleave(other: Iterable<A>): List<A>(source)

Interleaves the elements of this Iterable with those of other. Elements of this and other are taken in turn, and the resulting list is the concatenation of the interleaved elements. If one Iterable is longer than the other, the remaining elements are appended to the end.

import arrow.core.*
import io.kotest.matchers.shouldBe

fun test() {
val list1 = listOf(1, 2, 3)
val list2 = listOf(4, 5, 6, 7, 8)
list1.interleave(list2) shouldBe listOf(1, 4, 2, 5, 3, 6, 7, 8)
}

Interleaves the elements of this Sequence with those of other. Elements of this and other are taken in turn, and the resulting list is the concatenation of the interleaved elements. If one Sequence is longer than the other, the remaining elements are appended to the end.

import arrow.core.*
import io.kotest.matchers.shouldBe

fun test() {
val tags = generateSequence { "#" }.take(5)
val numbers = generateSequence(0) { it + 1 }.take(3)
tags.interleave(numbers).toList() shouldBe listOf("#", 0, "#", 1, "#", 2, "#", "#")
}