|
| 1 | +# Intersperse |
| 2 | + |
| 3 | +[[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncInterspersedSequence.swift) | |
| 4 | + [Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestInterspersed.swift)] |
| 5 | + |
| 6 | +Place a given value in between each element of the asynchronous sequence. |
| 7 | + |
| 8 | +```swift |
| 9 | +let numbers = [1, 2, 3].async.interspersed(with: 0) |
| 10 | +for await number in numbers { |
| 11 | + print(number) |
| 12 | +} |
| 13 | +// prints 1 0 2 0 3 |
| 14 | + |
| 15 | +let empty = [].async.interspersed(with: 0) |
| 16 | +// await Array(empty) == [] |
| 17 | +``` |
| 18 | + |
| 19 | +`interspersed(with:)` takes a separator value and inserts it in between every |
| 20 | +element in the asynchronous sequence. |
| 21 | + |
| 22 | +## Detailed Design |
| 23 | + |
| 24 | +A new method is added to `AsyncSequence`: |
| 25 | + |
| 26 | +```swift |
| 27 | +extension AsyncSequence { |
| 28 | + func interspersed(with separator: Element) -> AsyncInterspersedSequence<Self> |
| 29 | +} |
| 30 | +``` |
| 31 | + |
| 32 | +The new `AsyncInterspersedSequence` type represents the asynchronous sequence |
| 33 | +when the separator is inserted between each element. |
| 34 | + |
| 35 | +When the base asynchronous sequence can throw on iteration `AsyncInterspersedSequence` |
| 36 | +will throw on iteration; when the base does not throw then the iteration of |
| 37 | +`AsyncInterspersedSequence` does not. |
| 38 | + |
| 39 | +`AsyncInterspersedSequence` is conditionally `Sendable` when the base asynchronous |
| 40 | +sequence is `Sendable` and the element is also `Sendable`. |
| 41 | + |
| 42 | +### Naming |
| 43 | + |
| 44 | +This method’s and type’s name match the term of art used in other languages |
| 45 | +and libraries. |
| 46 | + |
| 47 | +This method is a direct analog to the synchronous version [defined in the Swift Algorithms package](https://github.com/apple/swift-algorithms/blob/main/Guides/Intersperse.md). |
| 48 | + |
| 49 | +### Comparison with other languages |
| 50 | + |
| 51 | +**[Haskell][Haskell]:** Has an `intersperse` function which takes an element |
| 52 | +and a list and 'intersperses' that element between the elements of the list. |
| 53 | + |
| 54 | +**[Rust][Rust]:** Has a function called `intersperse` to insert a particular |
| 55 | +value between each element. |
| 56 | + |
| 57 | +<!-- Link references for other languages --> |
| 58 | + |
| 59 | +[Haskell]: https://hackage.haskell.org/package/base-4.14.0.0/docs/Data-List.html#v:intersperse |
| 60 | +[Rust]: https://docs.rs/itertools/0.9.0/itertools/trait.Itertools.html#method.intersperse |
0 commit comments