Files
swift-algorithms/Guides/Intersperse.md
T

1.7 KiB
Raw Blame History

Intersperse

[Source | Tests]

Place a given value in between each element of the sequence.

let numbers = [1, 2, 3].interspersed(with: 0)
// Array(numbers) == [1, 0, 2, 0, 3]

let letters = "ABCDE".interspersed(with: "-")
// String(letters) == "A-B-C-D-E"

let empty = [].interspersed(with: 0)
// Array(empty) == []

interspersed(with:) takes a separator value and inserts it in between every element in the sequence.

Detailed Design

A new method is added to sequence:

extension Sequence {
    func interspersed(with separator: Element) -> Intersperse<Self>
}

The new Intersperse type represents the sequence when the separator is inserted between each element. Intersperse conforms to Collection and BidirectionalCollection when the base sequence conforms to Collection and BidirectionalCollection respectively.

Complexity

Calling these methods is O(1).

Naming

This method’s and type’s name match the term of art used in other languages and libraries.

Comparison with other languages

Haskell: Has an intersperse function which takes an element and a list and 'intersperses' that element between the elements of the list.

Rust: Has a function called intersperse to insert a particular value between each element.