Files
Tim Vermeulen c5ea9e3e36 Prepare for Swift Algorithms 1.0 (#167)
* Rename types to include a Sequence or Collection suffix, and clean up some guides

* Various refactors

* Replace `validateIndexTraversals` test method with `IndexValidator` type

* Add LazySequenceProtocol to StridingSequence, StridingCollection

* Update the Numerics dependency to 1.0

* Set `IndexedCollection.Indices` to `Base.Indices`

* Remove deprecations

* Update the changelog/README for the 1.0.0 release

* Fix compiler error on Linux

* Rename `WindowsCollection` to `WindowsOfCountCollection`
2021-09-09 01:01:36 +02:00

1.8 KiB
Raw Permalink 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) -> InterspersedSequence<Self>
}

The new InterspersedSequence type represents the sequence when the separator is inserted between each element. InterspersedSequence conforms to Collection, BidirectionalCollection, RandomAccessCollection and LazySequenceProtocol when the base sequence conforms to those respective protocols.

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.