mirror of
https://github.com/apple/swift-algorithms
synced 2026-11-22 04:10:39 +00:00
Compare commits
49
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bcd4f369ac | ||
|
|
4f53c9cf40 | ||
|
|
0d6f943832 | ||
|
|
fc8fdfd4dc | ||
|
|
bfcaaa8758 | ||
|
|
0f81ef4a70 | ||
|
|
de3efbc567 | ||
|
|
df51f1780b | ||
|
|
288d8b00f2 | ||
|
|
aa6349dea0 | ||
|
|
195e0316d7 | ||
|
|
da475ea9af | ||
|
|
19c1d00177 | ||
|
|
e2fa131d62 | ||
|
|
aeead5ab20 | ||
|
|
c5ea9e3e36 | ||
|
|
e195266e1f | ||
|
|
9f628005fe | ||
|
|
dcc3c82b0a | ||
|
|
50be2c8b3f | ||
|
|
2327673b0e | ||
|
|
4b779b8b3b | ||
|
|
0e2941ef50 | ||
|
|
e25cf27e57 | ||
|
|
3484ac31f6 | ||
|
|
f9f3a5ccc4 | ||
|
|
4038b5da40 | ||
|
|
65ef6cb966 | ||
|
|
0f27d99c89 | ||
|
|
66a56e36e7 | ||
|
|
9901a50b03 | ||
|
|
061501a712 | ||
|
|
dbc48be5dd | ||
|
|
04d91803a2 | ||
|
|
36bcc5581b | ||
|
|
31d600a4f1 | ||
|
|
0e44ceb7bb | ||
|
|
78dd4b5b93 | ||
|
|
abc5559ef6 | ||
|
|
bcdbac800a | ||
|
|
718220d0f8 | ||
|
|
551b4af927 | ||
|
|
dca25448e0 | ||
|
|
1639c1e2c3 | ||
|
|
a61c3db4fb | ||
|
|
198eee004e | ||
|
|
4cca4895cc | ||
|
|
001247f8a5 | ||
|
|
0065c60a22 |
No files matched your search
@@ -16,7 +16,7 @@ about: Something isn't working as expected
|
||||
|
||||
Replace this paragraph with a short description of the incorrect incorrect behavior. If this is a regression, please note the last version that the behavior was correct in addition to your current version.
|
||||
|
||||
**Swift Algorithms version:** `0.0.1` or the `main` branch, for example.
|
||||
**Swift Algorithms version:** `1.0.0` or the `main` branch, for example.
|
||||
**Swift version:** Paste the output of `swift --version` here.
|
||||
|
||||
### Checklist
|
||||
|
||||
@@ -17,5 +17,5 @@ Replace this paragraph with a description of your changes and rationale. Provide
|
||||
### Checklist
|
||||
- [ ] I've added at least one test that validates that my change is working, if appropriate
|
||||
- [ ] I've followed the code style of the rest of the project
|
||||
- [ ] I've read the [Contribution Guidelines](../CONTRIBUTING.md)
|
||||
- [ ] I've read the [Contribution Guidelines](../blob/main/CONTRIBUTING.md)
|
||||
- [ ] I've updated the documentation if necessary
|
||||
@@ -34,5 +34,5 @@ What is the impact of this change on existing users? Does it deprecate or remove
|
||||
### Checklist
|
||||
- [ ] I've added at least one test that validates that my change is working, if appropriate
|
||||
- [ ] I've followed the code style of the rest of the project
|
||||
- [ ] I've read the [Contribution Guidelines](../../CONTRIBUTING.md)
|
||||
- [ ] I've read the [Contribution Guidelines](../../blob/main/CONTRIBUTING.md)
|
||||
- [ ] I've updated the documentation if necessary
|
||||
@@ -0,0 +1,5 @@
|
||||
version: 1
|
||||
builder:
|
||||
configs:
|
||||
- documentation_targets: [Algorithms]
|
||||
|
||||
+260
-7
@@ -4,18 +4,234 @@
|
||||
Add new items at the end of the relevant section under **Unreleased**.
|
||||
-->
|
||||
|
||||
This project follows semantic versioning. While still in major version `0`,
|
||||
source-stability is only guaranteed within minor versions (e.g. between
|
||||
`0.0.3` and `0.0.4`). If you want to guard against potentially source-breaking
|
||||
package updates, you can specify your package dependency using
|
||||
`.upToNextMinor(from: "0.0.1")` as the requirement.
|
||||
This project follows semantic versioning.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
*No changes yet.*
|
||||
*No new changes.*
|
||||
|
||||
---
|
||||
|
||||
## [1.1.0] - 2023-08-24
|
||||
|
||||
### Additions
|
||||
|
||||
- New nonmutating `partitioned(by:)` methods that return both the failing and passing elements of a sequence or collection in separate arrays. ([#152])
|
||||
|
||||
```swift
|
||||
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
|
||||
let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })
|
||||
|
||||
print(longNames)
|
||||
// Prints "["Vivien", "Marlon"]"
|
||||
print(shortNames)
|
||||
// Prints "["Kim", "Karl"]"
|
||||
```
|
||||
|
||||
- A new `evenlyChunked(in:)` method that chunks a sequence or collection into the specified number of evenly-sized subsequences. ([#96])
|
||||
|
||||
```swift
|
||||
let numbers = Array(0..<10)
|
||||
for chunk in numbers.evenlyChunked(in: 4) {
|
||||
print(chunk)
|
||||
}
|
||||
// Prints:
|
||||
// [0, 1, 2]
|
||||
// [3, 4, 5]
|
||||
// [6, 7]
|
||||
// [8, 9]
|
||||
```
|
||||
|
||||
### Changes
|
||||
|
||||
- The package now has a minimum Swift version of Swift 5.4.
|
||||
|
||||
### Fixes
|
||||
|
||||
- Improvements to documentation, including a new DocC-based documentation structure.
|
||||
|
||||
The 1.1.0 release includes contributions from [dickoff], [gwynne], [mdznr], [natecook1000], [ole], [stephentyrone], and [timvermeulen].
|
||||
Thank you!
|
||||
|
||||
---
|
||||
|
||||
## [1.0.0] - 2021-09-08
|
||||
|
||||
### Changes
|
||||
|
||||
- Most sequence and collection types have been renamed, following a more
|
||||
consistent naming structure:
|
||||
- The `Lazy` prefix was dropped.
|
||||
- Either a `Sequence` or `Collection` suffix was added depending on whether or
|
||||
not the type is unconditionally a collection.
|
||||
- The base name was derived from the name of the method that produces it,
|
||||
including an argument label to disambiguate if necessary.
|
||||
```
|
||||
Chain2 -> Chain2Sequence
|
||||
ChunkedBy -> ChunkedByCollection
|
||||
ChunkedOn -> ChunkedOnCollection
|
||||
ChunkedByCount -> ChunksOfCountCollection
|
||||
Combinations -> CombinationsSequence
|
||||
Cycle -> CycledSequence
|
||||
FiniteCycle -> CycledTimesCollection
|
||||
Indexed -> IndexedCollection
|
||||
Intersperse -> InterspersedSequence
|
||||
LazySplitSequence -> SplitSequence
|
||||
LazySplitCollection -> SplitCollection
|
||||
Permutations -> PermutationsSequence
|
||||
UniquePermutations -> UniquePermutationsSequence
|
||||
Product2 -> Product2Sequence
|
||||
ExclusiveReductions -> ExclusiveReductionsSequence
|
||||
InclusiveReductions -> InclusiveReductionsSequence
|
||||
StrideSequence -> StridingSequence
|
||||
StrideCollection -> StridingCollection
|
||||
Uniqued -> UniquedSequence
|
||||
Windows -> WindowsOfCountCollection
|
||||
```
|
||||
- Types that can only be produced from a lazy sequence chain now unconditionally
|
||||
conform to `LazySequenceProtocol` and wrap the base sequence instead of the
|
||||
lazy wrapper, making some return types slightly simpler.
|
||||
- e.g. `[1, 2, 3].lazy.reductions(+)` now returns
|
||||
`ExclusiveReductionsSequence<[Int]>`, not
|
||||
`ExclusiveReductionsSequence<LazySequence<[Int]>>`.
|
||||
- This concerns `JoinedByClosureSequence`, `JoinedByClosureCollection`,
|
||||
`ExclusiveReductionsSequence`, `InclusiveReductionsSequence`.
|
||||
- The generic parameters of the `ExclusiveReductions` type have been swapped,
|
||||
putting the base collection first and the result type second.
|
||||
- The `Indices` associated type of `IndexedCollection` now matches
|
||||
`Base.Indices`.
|
||||
|
||||
### Removals
|
||||
|
||||
- Previously deprecated type and method names have been removed:
|
||||
- The `Chain` type alias for `Chain2Sequence`
|
||||
- The `chained(with:)` method which was replaced with the `chain(_:_:)` free
|
||||
function
|
||||
- The `LazyChunked` and `Chunked` type aliases for `ChunkedByCollection`
|
||||
- The `rotate(subrange:at:)` and `rotate(at:)` methods which were renamed to
|
||||
`rotate(subrange:toStartAt:)` and `rotate(toStartAt:)` respectively
|
||||
|
||||
### Fixes
|
||||
|
||||
- The `StridingSequence` and `StridingCollection` types now conditionally
|
||||
conform to `LazySequenceProtocol`, allowing the `striding(by:)` method to
|
||||
properly propagate laziness in a lazy sequence chain.
|
||||
- Fixed `chunked(by:)` to always compare two consecutive elements rather than
|
||||
each element with the first element of the current chunk. ([#162])
|
||||
|
||||
The 1.0.0 release includes contributions from [iainsmith], [mdznr], and
|
||||
[timvermeulen]. Thank you!
|
||||
|
||||
## [0.2.1] - 2021-06-01
|
||||
|
||||
### Additions
|
||||
|
||||
Expanded versatility for two existing operations:
|
||||
|
||||
- A series of `joined(by:)` overloads concatenate a sequence of sequences using
|
||||
an element or a collection, either passed in or generated from consecutive
|
||||
elements via a closure. ([#138])
|
||||
- Additional `trimming(while:)` methods for trimming only the start or end of a
|
||||
collection, as well as mutating versions of all three variants. ([#104])
|
||||
|
||||
The 0.2.1 release includes contributions from [fedeci] and [timvermeulen].
|
||||
Thank you!
|
||||
|
||||
## [0.2.0] - 2021-05-17
|
||||
|
||||
### Additions
|
||||
|
||||
Two new additions to the list of algorithms:
|
||||
|
||||
- `adjacentPairs()` lazily iterates over tuples of adjacent elements of a
|
||||
sequence. ([#119])
|
||||
- `minAndMax()` finds both the smallest and largest elements of a sequence in
|
||||
a single pass. ([#90])
|
||||
|
||||
### Changes
|
||||
|
||||
- When calling `chunked(on:)`, the resulting collection has an element type of
|
||||
`(Subject, SubSequence)` instead of just `SubSequence`, making the subject
|
||||
value available when iterating.
|
||||
|
||||
```swift
|
||||
let numbers = [5, 6, -3, -9, -11, 2, 7, 6]
|
||||
for (signum, values) in numbers.chunked(on: { $0.signum() }) {
|
||||
print(signum, values)
|
||||
}
|
||||
// 1 [5, 6]
|
||||
// -1 [-3, -9, -11]
|
||||
// 1 [2, 7, 6]
|
||||
```
|
||||
|
||||
### Fixes
|
||||
|
||||
- Improvements to the documentation and PR templates.
|
||||
|
||||
The 0.2.0 release includes contributions from [CTMacUser], [LemonSpike],
|
||||
[mpangburn], and [natecook1000]. Thank you!
|
||||
|
||||
---
|
||||
|
||||
## [0.1.1] - 2021-04-14
|
||||
|
||||
### Fixes
|
||||
|
||||
- `Product2` associated type inference error in release build ([#130])
|
||||
|
||||
## [0.1.0] - 2021-04-13
|
||||
|
||||
### Additions
|
||||
|
||||
- The `compacted()` method lazily finds the non-`nil` elements of a sequence or
|
||||
collection ([#112]).
|
||||
|
||||
### Changes
|
||||
|
||||
- The `uniqued()` method now lazily computes the unique elements of a sequence
|
||||
or a collection ([#71]). Pass this resulting sequence to an `Array`
|
||||
initializer to recover the behavior of the previous release.
|
||||
- Calling `cycled(times:)` now returns a new `FiniteCycle` type, which has the
|
||||
same conformances as its underlying collection ([#106]).
|
||||
- The base collections of the sequence and collection wrapper types are no
|
||||
longer public ([#85], [#125]), and the wrapper types no longer conform to the
|
||||
`Equatable` or `Hashable` protocols ([#124]). If you need those conformances,
|
||||
convert the wrapper type to an `Array` or other collection currrency type
|
||||
before storing. Please file an issue if these changes pose a problem for your
|
||||
use case.
|
||||
|
||||
The 0.1.0 release includes contributions from [LemonSpike], [LucianoPAlmeida],
|
||||
[natecook1000], and [timvermeulen]. Thank you!
|
||||
|
||||
---
|
||||
|
||||
## [0.0.4] - 2021-03-29
|
||||
|
||||
### Additions
|
||||
|
||||
More new algorithms to join the party:
|
||||
|
||||
- A lazy version of the standard library's two `split` methods. ([#78])
|
||||
- `firstNonNil(_:)` returns the first non-`nil` element from an
|
||||
optional-generating transform. ([#31])
|
||||
- `uniquePermutations()` skips duplicates when generating permutations of a
|
||||
collection. ([#91])
|
||||
- The `reductions` methods return all the in-between states of reducing a
|
||||
sequence or collection. ([#46])
|
||||
|
||||
### Fixes
|
||||
|
||||
- Methods and computed properties are more consistently marked as inlinable,
|
||||
resolving a performance regression.
|
||||
- The `Stride` type now efficiently calculates distances between positions,
|
||||
supported by the underlying collection.
|
||||
- Better test coverage and improved diagnostics for comparing sequences.
|
||||
- Fixed links and improved documentation.
|
||||
|
||||
The 0.0.4 release includes contributions from [bjhomer], [danielctull],
|
||||
[hashemi], [karwa], [kylemacomber], [LucianoPAlmeida], [mdznr], [natecook1000],
|
||||
[ollieatkinson], [Qata], [timvermeulen], and [toddthomas]. Thank you!
|
||||
|
||||
## [0.0.3] - 2021-02-26
|
||||
|
||||
### Additions
|
||||
@@ -96,7 +312,14 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
|
||||
|
||||
<!-- Link references for releases -->
|
||||
|
||||
[Unreleased]: https://github.com/apple/swift-algorithms/compare/0.0.3...HEAD
|
||||
[Unreleased]: https://github.com/apple/swift-algorithms/compare/1.1.0...HEAD
|
||||
[1.1.0]: https://github.com/apple/swift-algorithms/compare/1.0.0...1.1.0
|
||||
[1.0.0]: https://github.com/apple/swift-algorithms/compare/0.2.1...1.0.0
|
||||
[0.2.1]: https://github.com/apple/swift-algorithms/compare/0.2.0...0.2.1
|
||||
[0.2.0]: https://github.com/apple/swift-algorithms/compare/0.1.1...0.2.0
|
||||
[0.1.1]: https://github.com/apple/swift-algorithms/compare/0.1.0...0.1.1
|
||||
[0.1.0]: https://github.com/apple/swift-algorithms/compare/0.0.4...0.1.0
|
||||
[0.0.4]: https://github.com/apple/swift-algorithms/compare/0.0.3...0.0.4
|
||||
[0.0.3]: https://github.com/apple/swift-algorithms/compare/0.0.2...0.0.3
|
||||
[0.0.2]: https://github.com/apple/swift-algorithms/compare/0.0.1...0.0.2
|
||||
[0.0.1]: https://github.com/apple/swift-algorithms/releases/tag/0.0.1
|
||||
@@ -107,32 +330,61 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
|
||||
[#9]: https://github.com/apple/swift-algorithms/pull/9
|
||||
[#20]: https://github.com/apple/swift-algorithms/pull/20
|
||||
[#24]: https://github.com/apple/swift-algorithms/pull/24
|
||||
[#31]: https://github.com/apple/swift-algorithms/pull/31
|
||||
[#35]: https://github.com/apple/swift-algorithms/pull/35
|
||||
[#46]: https://github.com/apple/swift-algorithms/pull/46
|
||||
[#51]: https://github.com/apple/swift-algorithms/pull/51
|
||||
[#54]: https://github.com/apple/swift-algorithms/pull/54
|
||||
[#56]: https://github.com/apple/swift-algorithms/pull/56
|
||||
[#65]: https://github.com/apple/swift-algorithms/pull/65
|
||||
[#71]: https://github.com/apple/swift-algorithms/pull/71
|
||||
[#77]: https://github.com/apple/swift-algorithms/pull/77
|
||||
[#78]: https://github.com/apple/swift-algorithms/pull/78
|
||||
[#85]: https://github.com/apple/swift-algorithms/pull/85
|
||||
[#90]: https://github.com/apple/swift-algorithms/pull/90
|
||||
[#91]: https://github.com/apple/swift-algorithms/pull/91
|
||||
[#96]: https://github.com/apple/swift-algorithms/pull/96
|
||||
[#104]: https://github.com/apple/swift-algorithms/pull/104
|
||||
[#106]: https://github.com/apple/swift-algorithms/pull/106
|
||||
[#112]: https://github.com/apple/swift-algorithms/pull/112
|
||||
[#119]: https://github.com/apple/swift-algorithms/pull/119
|
||||
[#124]: https://github.com/apple/swift-algorithms/pull/124
|
||||
[#125]: https://github.com/apple/swift-algorithms/pull/125
|
||||
[#130]: https://github.com/apple/swift-algorithms/pull/130
|
||||
[#138]: https://github.com/apple/swift-algorithms/pull/138
|
||||
[#152]: https://github.com/apple/swift-algorithms/pull/152
|
||||
[#162]: https://github.com/apple/swift-algorithms/pull/162
|
||||
|
||||
<!-- Link references for contributors -->
|
||||
|
||||
[AustinConlon]: https://github.com/apple/swift-algorithms/commits?author=AustinConlon
|
||||
[benrimmington]: https://github.com/apple/swift-algorithms/commits?author=benrimmington
|
||||
[bjhomer]: https://github.com/apple/swift-algorithms/commits?author=bjhomer
|
||||
[CTMacUser]: https://github.com/apple/swift-algorithms/commits?author=CTMacUser
|
||||
[danielctull]: https://github.com/apple/swift-algorithms/commits?author=danielctull
|
||||
[dhruvshah8]: https://github.com/apple/swift-algorithms/commits?author=dhruvshah8
|
||||
[dickoff]: https://github.com/apple/swift-algorithms/commits?author=dickoff
|
||||
[egorzhdan]: https://github.com/apple/swift-algorithms/commits?author=egorzhdan
|
||||
[fedeci]: https://github.com/apple/swift-algorithms/commits?author=fedeci
|
||||
[gwynne]: https://github.com/apple/swift-algorithms/commits?author=gwynne
|
||||
[hashemi]: https://github.com/apple/swift-algorithms/commits?author=hashemi
|
||||
[iainsmith]: https://github.com/apple/swift-algorithms/commits?author=iainsmith
|
||||
[IanKeen]: https://github.com/apple/swift-algorithms/commits?author=IanKeen
|
||||
[iSame7]: https://github.com/apple/swift-algorithms/commits?author=iSame7
|
||||
[karwa]: https://github.com/apple/swift-algorithms/commits?author=karwa
|
||||
[kylemacomber]: https://github.com/apple/swift-algorithms/commits?author=kylemacomber
|
||||
[LemonSpike]: https://github.com/apple/swift-algorithms/commits?author=LemonSpike
|
||||
[LucianoPAlmeida]: https://github.com/apple/swift-algorithms/commits?author=LucianoPAlmeida
|
||||
[markuswntr]: https://github.com/apple/swift-algorithms/commits?author=markuswntr
|
||||
[mdznr]: https://github.com/apple/swift-algorithms/commits?author=mdznr
|
||||
[michiboo]: https://github.com/apple/swift-algorithms/commits?author=michiboo
|
||||
[mpangburn]: https://github.com/apple/swift-algorithms/commits?author=mpangburn
|
||||
[natecook1000]: https://github.com/apple/swift-algorithms/commits?author=natecook1000
|
||||
[nordicio]: https://github.com/apple/swift-algorithms/commits?author=nordicio
|
||||
[ole]: https://github.com/apple/swift-algorithms/commits?author=ole
|
||||
[ollieatkinson]: https://github.com/apple/swift-algorithms/commits?author=ollieatkinson
|
||||
[pmtao]: https://github.com/apple/swift-algorithms/commits?author=pmtao
|
||||
[Qata]: https://github.com/apple/swift-algorithms/commits?author=Qata
|
||||
[rakaramos]: https://github.com/apple/swift-algorithms/commits?author=rakaramos
|
||||
[rockbruno]: https://github.com/apple/swift-algorithms/commits?author=rockbruno
|
||||
[Roshankumar350]: https://github.com/apple/swift-algorithms/commits?author=Roshankumar350
|
||||
@@ -140,3 +392,4 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
|
||||
[sidepelican]: https://github.com/apple/swift-algorithms/commits?author=sidepelican
|
||||
[stephentyrone]: https://github.com/apple/swift-algorithms/commits?author=stephentyrone
|
||||
[timvermeulen]: https://github.com/apple/swift-algorithms/commits?author=timvermeulen
|
||||
[toddthomas]: https://github.com/apple/swift-algorithms/commits?author=toddthomas
|
||||
@@ -0,0 +1,63 @@
|
||||
# AdjacentPairs
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/AdjacentPairs.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/AdjacentPairsTests.swift)]
|
||||
|
||||
Lazily iterates over tuples of adjacent elements.
|
||||
|
||||
This operation is available for any sequence by calling the `adjacentPairs()`
|
||||
method.
|
||||
|
||||
```swift
|
||||
let numbers = (1...5)
|
||||
let pairs = numbers.adjacentPairs()
|
||||
// Array(pairs) == [(1, 2), (2, 3), (3, 4), (4, 5)]
|
||||
```
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The `adjacentPairs()` method is declared as a `Sequence` extension returning
|
||||
`AdjacentPairsSequence` and as a `Collection` extension returning
|
||||
`AdjacentPairsCollection`.
|
||||
|
||||
```swift
|
||||
extension Sequence {
|
||||
public func adjacentPairs() -> AdjacentPairsSequence<Self>
|
||||
}
|
||||
```
|
||||
|
||||
```swift
|
||||
extension Collection {
|
||||
public func adjacentPairs() -> AdjacentPairsCollection<Self>
|
||||
}
|
||||
```
|
||||
|
||||
The `AdjacentPairsSequence` type is a sequence, and the
|
||||
`AdjacentPairsCollection` type is a collection with conditional conformance to
|
||||
`BidirectionalCollection` and `RandomAccessCollection` when the underlying
|
||||
collection conforms.
|
||||
|
||||
### Complexity
|
||||
|
||||
Calling `adjacentPairs` is an O(1) operation.
|
||||
|
||||
### Naming
|
||||
|
||||
This method is named for clarity while remaining agnostic to any particular
|
||||
domain of programming. In natural language processing, this operation is akin to
|
||||
computing a list of bigrams; however, this algorithm is not specific to this use
|
||||
case.
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
This function is often written as a `zip` of a sequence together with itself,
|
||||
minus its first element.
|
||||
|
||||
**Haskell:** This operation is spelled ``s `zip` tail s``.
|
||||
|
||||
**Python:** Python users may write `zip(s, s[1:])` for a list with at least one
|
||||
element. For natural language processing, the `nltk` package offers a `bigrams`
|
||||
function akin to this method.
|
||||
|
||||
Note that in Swift, the spelling `zip(s, s.dropFirst())` is undefined behavior
|
||||
for a single-pass sequence `s`.
|
||||
+4
-4
@@ -25,13 +25,13 @@ the shared conformances of the two underlying types.
|
||||
The `chain(_:_:)` function takes two sequences as arguments:
|
||||
|
||||
```swift
|
||||
public func chain<S1, S2>(_ s1: S1, _ s2: S2) -> Chain2<S1, S2>
|
||||
public func chain<S1, S2>(_ s1: S1, _ s2: S2) -> Chain2Sequence<S1, S2>
|
||||
where S1.Element == S2.Element
|
||||
```
|
||||
|
||||
The resulting `Chain2` type is a sequence, with conditional conformance to
|
||||
`Collection`, `BidirectionalCollection`, and `RandomAccessCollection` when both
|
||||
the first and second arguments conform.
|
||||
The resulting `Chain2Sequence` type is a sequence, with conditional conformance
|
||||
to `Collection`, `BidirectionalCollection`, and `RandomAccessCollection` when
|
||||
both the first and second arguments conform.
|
||||
|
||||
### Naming
|
||||
|
||||
|
||||
+69
-37
@@ -3,16 +3,16 @@
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Chunked.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/ChunkedTests.swift)]
|
||||
|
||||
Break a collection into subsequences where consecutive elements pass a binary
|
||||
predicate, or where all elements in each chunk project to the same value.
|
||||
Break a collection into nonoverlapping subsequences:
|
||||
|
||||
Also, includes a `chunks(ofCount:)` that breaks a collection into subsequences
|
||||
of a given `count`.
|
||||
* `chunked(by:)` forms chunks of consecutive elements that pass a binary predicate,
|
||||
* `chunked(on:)` forms chunks of consecutive elements that project to equal values,
|
||||
* `chunks(ofCount:)` forms chunks of a given size, and
|
||||
* `evenlyChunked(in:)` forms a given number of equally-sized chunks.
|
||||
|
||||
There are two variations of the `chunked` method: `chunked(by:)` and
|
||||
`chunked(on:)`. `chunked(by:)` uses a binary predicate to test consecutive
|
||||
elements, separating chunks where the predicate returns `false`. For example,
|
||||
you can chunk a collection into ascending sequences using this method:
|
||||
`chunked(by:)` uses a binary predicate to test consecutive elements, separating
|
||||
chunks where the predicate returns `false`. For example, you can chunk a
|
||||
collection into ascending sequences using this method:
|
||||
|
||||
```swift
|
||||
let numbers = [10, 20, 30, 10, 40, 40, 10, 20]
|
||||
@@ -20,20 +20,21 @@ let chunks = numbers.chunked(by: { $0 <= $1 })
|
||||
// [[10, 20, 30], [10, 40, 40], [10, 20]]
|
||||
```
|
||||
|
||||
The `chunk(on:)` method, by contrast, takes a projection of each element and
|
||||
The `chunked(on:)` method, by contrast, takes a projection of each element and
|
||||
separates chunks where the projection of two consecutive elements is not equal.
|
||||
The result includes both the projected value and the subsequence that groups
|
||||
elements with that projected value:
|
||||
|
||||
```swift
|
||||
let names = ["David", "Kyle", "Karoy", "Nate"]
|
||||
let chunks = names.chunked(on: \.first!)
|
||||
// [["David"], ["Kyle", "Karoy"], ["Nate"]]
|
||||
// [("D", ["David"]), ("K", ["Kyle", "Karoy"]), ("N", ["Nate"])]
|
||||
```
|
||||
|
||||
The `chunks(ofCount:)` takes a `count` parameter (required to be > 0) and separates
|
||||
the collection into `n` chunks of this given count. If the `count` parameter is
|
||||
evenly divided by the count of the base `Collection` all the chunks will have
|
||||
the count equals to the parameter. Otherwise, the last chunk will contain the
|
||||
remaining elements.
|
||||
The `chunks(ofCount:)` method takes a `count` parameter (required to be > 0) and
|
||||
separates the collection into chunks of this given count. If the length of the
|
||||
collection is a multiple of the `count` parameter, all chunks will have the
|
||||
a count equal to the parameter. Otherwise, the last chunk will contain the remaining elements.
|
||||
|
||||
```swift
|
||||
let names = ["David", "Kyle", "Karoy", "Nate"]
|
||||
@@ -44,23 +45,39 @@ let remaining = names.chunks(ofCount: 3)
|
||||
// equivalent to [["David", "Kyle", "Karoy"], ["Nate"]]
|
||||
```
|
||||
|
||||
The `chunks(ofCount:)` is the method of the [existing SE proposal][proposal].
|
||||
Unlike the `split` family of methods, the entire collection is included in the
|
||||
chunked result — joining the resulting chunks recreates the original collection.
|
||||
The `chunks(ofCount:)` method was previously [proposed](proposal) for inclusion
|
||||
in the standard library.
|
||||
|
||||
The `evenlyChunked(in:)` method takes a `count` parameter and divides the
|
||||
collection into `count` number of equally-sized chunks. If the length of the
|
||||
collection is not a multiple of the `count` parameter, the chunks at the start
|
||||
will be longer than the chunks at the end.
|
||||
|
||||
```swift
|
||||
let evenChunks = (0..<15).evenlyChunked(in: 3)
|
||||
// equivalent to [0..<5, 5..<10, 10..<15]
|
||||
|
||||
let nearlyEvenChunks = (0..<15).evenlyChunked(in: 4)
|
||||
// equivalent to [0..<4, 4..<8, 8..<12, 12..<15]
|
||||
```
|
||||
|
||||
When "chunking" a collection, the entire collection is included in the result,
|
||||
unlike the `split` family of methods, where separators are dropped.
|
||||
Joining the result of a chunking method call results in a collection equivalent
|
||||
to the original.
|
||||
|
||||
```swift
|
||||
c.elementsEqual(c.chunked(...).joined())
|
||||
// true
|
||||
```
|
||||
|
||||
Check the [proposal][proposal] detailed design section for more info.
|
||||
|
||||
[proposal]: https://github.com/apple/swift-evolution/pull/935
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The two methods are added as extension to `Collection`, with two matching
|
||||
versions that return a lazy wrapper added to `LazyCollectionProtocol`.
|
||||
The four methods are added to `Collection`, with matching versions of
|
||||
`chunked(by:)` and `chunked(on:)` that return a lazy wrapper added to
|
||||
`LazyCollectionProtocol`.
|
||||
|
||||
```swift
|
||||
extension Collection {
|
||||
@@ -69,41 +86,56 @@ extension Collection {
|
||||
) -> [SubSequence]
|
||||
|
||||
public func chunked<Subject: Equatable>(
|
||||
on projection: (Element) -> Subject
|
||||
on projection: (Element) -> Subject
|
||||
) -> [SubSequence]
|
||||
}
|
||||
|
||||
public func chunks(ofCount count: Int) -> ChunkedByCount<Self>
|
||||
|
||||
public func evenlyChunked(in count: Int) -> EvenlyChunkedCollection<Self>
|
||||
}
|
||||
|
||||
extension LazyCollectionProtocol {
|
||||
extension LazyCollectionProtocol {
|
||||
public func chunked(
|
||||
by belongInSameGroup: @escaping (Element, Element) -> Bool
|
||||
) -> LazyChunked<Elements>
|
||||
) -> ChunkedByCollection<Elements>
|
||||
|
||||
public func chunked<Subject: Equatable>(
|
||||
on projection: @escaping (Element) -> Subject
|
||||
) -> LazyChunked<Elements>
|
||||
) -> ChunkedOnCollection<Elements, Subject>
|
||||
}
|
||||
```
|
||||
|
||||
The `LazyChunked` type is bidirectional when the wrapped collection is
|
||||
bidirectional.
|
||||
Each of the "chunked" collection types are bidirectional when the wrapped
|
||||
collection is bidirectional. `ChunksOfCountCollection` and
|
||||
`EvenlyChunkedCollection` also conform to `RandomAccessCollection` and
|
||||
`LazySequenceProtocol` when their base collections conform.
|
||||
|
||||
### Complexity
|
||||
|
||||
The eager methods are O(_n_), the lazy methods are O(_1_).
|
||||
The eager methods are O(_n_) where _n_ is the number of elements in the
|
||||
collection. The lazy methods are O(_n_) because the start index is pre-computed.
|
||||
|
||||
### Naming
|
||||
|
||||
The operation performed by these methods is similar to other ways of breaking a collection up into subsequences. In particular, the predicate-based `split(where:)` method looks similar to `chunked(on:)`. You can draw a distinction between these different operations based on the resulting subsequences:
|
||||
|
||||
- `split`: *In the standard library.* Breaks a collection into subsequences, removing any elements that are considered "separators". The original collection cannot be recovered from the result of splitting.
|
||||
- `chunked`: *In this package.* Breaks a collection into subsequences, preserving each element in its initial ordering. Joining the resulting subsequences re-forms the original collection.
|
||||
- `sliced`: *Not included in this package or the stdlib.* Breaks a collection into potentially overlapping subsequences.
|
||||
The operation performed by these methods is similar to other ways of breaking a
|
||||
collection up into subsequences. In particular, the predicate-based
|
||||
`split(where:)` method looks similar to `chunked(on:)`. You can draw a
|
||||
distinction between these different operations based on the resulting
|
||||
subsequences:
|
||||
|
||||
- `split`: *In the standard library.* Breaks a collection into subsequences,
|
||||
removing any elements that are considered "separators". The original collection
|
||||
cannot be recovered from the result of splitting.
|
||||
- `chunked`: *In this package.* Breaks a collection into subsequences,
|
||||
preserving each element in its initial ordering. Joining the resulting
|
||||
subsequences re-forms the original collection.
|
||||
- `sliced`: *Not included in this package or the stdlib.* Breaks a collection
|
||||
into potentially overlapping subsequences.
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
**Ruby:** Ruby’s `Enumerable` class defines `chunk_while` and `chunk`, which map
|
||||
to the proposed `chunked(by:)` and `chunked(on:)` methods.
|
||||
|
||||
**Rust:** Rust defines a variety of size-based `chunks` methods, but doesn’t
|
||||
include any with the functionality described here.
|
||||
**Rust:** Rust defines a variety of size-based `chunks` methods, of which the
|
||||
standard version corresponds to the `chunks(ofCount:)` method defined here.
|
||||
+11
-10
@@ -60,27 +60,28 @@ for combo in numbers.combinations(ofCount: 2...3) {
|
||||
## Detailed Design
|
||||
|
||||
The `combinations(ofCount:)` method is declared as a `Collection` extension,
|
||||
and returns a `Combinations` type:
|
||||
and returns a `CombinationsSequence` type:
|
||||
|
||||
```swift
|
||||
extension Collection {
|
||||
public func combinations(ofCount k: Int) -> Combinations<Self>
|
||||
public func combinations(ofCount k: Int) -> CombinationsSequence<Self>
|
||||
}
|
||||
```
|
||||
|
||||
Since the `Combinations` type needs to store an array of the collection’s
|
||||
indices and mutate the array to generate each permutation, `Combinations` only
|
||||
has `Sequence` conformance. Adding `Collection` conformance would require
|
||||
storing the array in the index type, which would in turn lead to copying the
|
||||
array at every index advancement. `Combinations` does conform to
|
||||
`LazySequenceProtocol` when the base type conforms.
|
||||
Since the `CombinationsSequence` type needs to store an array of the
|
||||
collection’s indices and mutate the array to generate each permutation,
|
||||
`CombinationsSequence` only has `Sequence` conformance. Adding `Collection`
|
||||
conformance would require storing the array in the index type, which would in
|
||||
turn lead to copying the array at every index advancement.
|
||||
`CombinationsSequence` does conform to `LazySequenceProtocol` when the base type
|
||||
conforms.
|
||||
|
||||
### Complexity
|
||||
|
||||
Calling `combinations(ofCount:)` accesses the count of the collection, so it’s
|
||||
an O(1) operation for random-access collections, or an O(_n_) operation
|
||||
otherwise. Creating the iterator for a `Combinations` instance and each call to
|
||||
`Combinations.Iterator.next()` is an O(_n_) operation.
|
||||
otherwise. Creating the iterator for a `CombinationsSequence` instance and each
|
||||
call to `CombinationsSequence.Iterator.next()` is an O(_n_) operation.
|
||||
|
||||
### Naming
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# Compacted
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Compacted.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/CompactedTests.swift)]
|
||||
|
||||
A convenience method that lazily flattens the `nil`s out of a sequence
|
||||
or collection.
|
||||
|
||||
The new method matches one of the most common uses of `compactMap`,
|
||||
which is to only remove `nil`s without transforming the elements
|
||||
(e.g. `collection.lazy.compactMap { $0 }`).
|
||||
|
||||
```swift
|
||||
let array: [Int?] = [10, nil, 30, nil, 2, 3, nil, 5]
|
||||
let withNoNils = array.compacted()
|
||||
// Array(withNoNils) == [10, 30, 2, 3, 5]
|
||||
```
|
||||
|
||||
The type returned by `compacted()` lazily computes the non-`nil` elements
|
||||
without requiring a user to provide a closure or use the `.lazy` property.
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The `compacted()` methods has two overloads:
|
||||
|
||||
```swift
|
||||
extension Sequence {
|
||||
public func compacted<Unwrapped>() -> CompactedSequence<Self, Unwrapped>
|
||||
where Element == Unwrapped?
|
||||
}
|
||||
|
||||
extension Collection {
|
||||
public func compacted<Unwrapped>() -> CompactedCollection<Self, Unwrapped>
|
||||
where Element == Unwrapped?
|
||||
}
|
||||
```
|
||||
|
||||
The `Sequence` version of `compacted()` returns a `CompactedSequence` type,
|
||||
while the `Collection` version returns `CompactedCollection`. The collection
|
||||
has conditional conformance to `BidirectionalCollection` when the base
|
||||
collection conforms, and both have conditional conformance to
|
||||
`LazySequenceProtocol` when the base collection conforms.
|
||||
|
||||
### Naming
|
||||
|
||||
The name `compacted()` matches the existing method `compactMap`,
|
||||
which is commonly used to extract only the non-`nil` values
|
||||
without mapping them to a different type.
|
||||
+13
-12
@@ -16,9 +16,9 @@ for x in (1...3).cycled(times: 3) {
|
||||
// Prints 1 through 3 three times
|
||||
```
|
||||
|
||||
`cycled(times:)` combines two other existing standard library functions
|
||||
(`repeatElement` and `joined`) to provide a more expressive way of repeating a
|
||||
collection's elements a limited number of times.
|
||||
`cycled(times:)` provides a more expressive way of repeating a
|
||||
collection's elements a limited number of times than
|
||||
combining `repeatElement(_:count:)` and `joined()`.
|
||||
|
||||
## Detailed Design
|
||||
|
||||
@@ -26,19 +26,20 @@ Two new methods are added to collections:
|
||||
|
||||
```swift
|
||||
extension Collection {
|
||||
func cycled() -> Cycle<Self>
|
||||
func cycled() -> CycledSequence<Self>
|
||||
|
||||
func cycled(times: Int) -> FlattenSequence<Repeated<Self>>
|
||||
func cycled(times: Int) -> CycledTimesCollection<Self>
|
||||
}
|
||||
```
|
||||
|
||||
The new `Cycle` type is a sequence only, given that the `Collection` protocol
|
||||
design makes infinitely large types impossible/impractical. `Cycle` also
|
||||
conforms to `LazySequenceProtocol` when the base type conforms.
|
||||
The new `CycledSequence` type is a sequence only, given that the `Collection`
|
||||
protocol design makes infinitely large types impossible/impractical.
|
||||
`CycledSequence` also conforms to `LazySequenceProtocol` when the base type
|
||||
conforms.
|
||||
|
||||
Note that despite its name, the returned `FlattenSequence` will always have
|
||||
`Collection` conformance, and will have `BidirectionalCollection` conformance
|
||||
when called on a bidirectional collection.
|
||||
The `CycledTimesCollection` type always has `Collection` conformance, with
|
||||
`BidirectionalCollection`, `RandomAccessCollection`, and `LazySequenceProtocol`
|
||||
conformance when the base type conforms.
|
||||
|
||||
### Complexity
|
||||
|
||||
@@ -61,4 +62,4 @@ anything that matches the `cycled(times:)` behavior.
|
||||
`cycled(times:)` here.
|
||||
|
||||
**Python:** Python’s `itertools` includes a `cycle` method, which caches the
|
||||
elements of the iterator on the first pass.
|
||||
elements of the iterator on the first pass.
|
||||
+60
-18
@@ -2,23 +2,48 @@
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/FirstNonNil.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/FirstNonNilTests.swift)]
|
||||
|
||||
Retrieves the first `.some` encountered while applying the given transform.
|
||||
|
||||
This operation is available through the `firstNonNil(_:)` method on any sequence.
|
||||
|
||||
Returns the first non-`nil` result obtained from applying the given
|
||||
transformation to the elements of the sequence.
|
||||
|
||||
```swift
|
||||
let value = ["A", "B", "10"].firstNonNil { Int($0) }
|
||||
// value == .some(10)
|
||||
//
|
||||
let noValue = ["A", "B", "C"].firstNonNil { Int($0) }
|
||||
// noValue == .none
|
||||
let strings = ["three", "3.14", "-5", "2"]
|
||||
if let firstInt = strings.firstNonNil({ Int($0) }) {
|
||||
print(firstInt)
|
||||
// -5
|
||||
}
|
||||
```
|
||||
|
||||
Like `first(where:)`, this method stops iterating the sequence once a match is
|
||||
found. Use `firstNonNil(_:)` to avoid having to apply a transformation twice:
|
||||
|
||||
This method is analogous to `first(where:)` in how it only consumes values until
|
||||
a `.some` is found, unlike using lazy operators, which will load any sequence into a collection
|
||||
before evaluating its transforms lazily.
|
||||
```swift
|
||||
let strings = ["three", "3.14", "-5", "2"]
|
||||
if let firstIntAsString = strings.first(where: { Int($0) != nil }) {
|
||||
let firstInt = Int(firstIntAsString)! // :(
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
This method's behavior can also be approximated using `compactMap(_:)`:
|
||||
|
||||
```swift
|
||||
let strings = ["three", "3.14", "-5", "2"]
|
||||
if let firstInt = strings.compactMap({ Int($0) }).first {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
However, unlike `firstNonNil(_:)` and `first(where:)`, `compactMap(_:)` does not
|
||||
stop iterating the sequence once the first match is found. Adding `.lazy` fixes
|
||||
this, at the cost of requiring an escaping closure that you cannot `throw` from:
|
||||
|
||||
```swift
|
||||
let strings = ["three", "3.14", "-5", "2"]
|
||||
if let firstInt = strings.lazy.compactMap({ Int($0) }).first {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
## Detailed Design
|
||||
|
||||
@@ -27,17 +52,34 @@ protocol:
|
||||
|
||||
```swift
|
||||
public extension Sequence {
|
||||
func firstNonNil<Result>(_ transform: (Element) throws -> Result?)
|
||||
rethrows -> Result?
|
||||
func firstNonNil<Result>(
|
||||
_ transform: (Element) throws -> Result?
|
||||
) rethrows -> Result?
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Complexity
|
||||
|
||||
`firstNonNil(_:)` is an O(*n*) operation, where *n* is the number of
|
||||
elements at the start of the sequence that result in `nil` when applying the
|
||||
transformation.
|
||||
|
||||
### Naming
|
||||
|
||||
This method’s name was selected for its comprehensibility.
|
||||
Some alternative names were considered:
|
||||
|
||||
* `compactMapFirst(_:)`
|
||||
* `first(mapping:)`
|
||||
* `firstSome(_:)`
|
||||
* `firstMap(_:)`
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
**Scala**: Scala provides a `collectFirst` function that finds the first element
|
||||
in a collection for which a partial function is defined.
|
||||
**Haskell**: Haskell includes the `firstJust` method, which has the same
|
||||
semantics as the `firstNonNil(_:)` method.
|
||||
|
||||
**Rust**: Rust includes the `find_map` method, which has the same semantics as
|
||||
the `firstNonNil(_:)` method.
|
||||
|
||||
**Scala**: Scala includes the `collectFirst` method, which has the same
|
||||
semantics as the `firstNonNil(_:)` method.
|
||||
+5
-5
@@ -21,15 +21,15 @@ for (i, n) in numbers.indexed() {
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The `indexed` method returns an `Indexed` type:
|
||||
The `indexed` method returns an `IndexedCollection` type:
|
||||
|
||||
```swift
|
||||
extension Collection {
|
||||
func indexed() -> Indexed<Self>
|
||||
func indexed() -> IndexedCollection<Self>
|
||||
}
|
||||
```
|
||||
|
||||
`Indexed` scales from a collection up to a random-access collection, depending on
|
||||
its base type. `Indexed` also conforms to `LazySequenceProtocol` and
|
||||
`LazyCollectionProtocol` when the base type conforms.
|
||||
`IndexedCollection` scales from a collection up to a random-access collection,
|
||||
depending on its base type. `Indexed` also conforms to `LazySequenceProtocol`
|
||||
when the base type conforms.
|
||||
|
||||
@@ -25,14 +25,14 @@ A new method is added to sequence:
|
||||
|
||||
```swift
|
||||
extension Sequence {
|
||||
func interspersed(with separator: Element) -> Intersperse<Self>
|
||||
func interspersed(with separator: Element) -> InterspersedSequence<Self>
|
||||
}
|
||||
```
|
||||
|
||||
The new `Intersperse` type represents the sequence when the separator is
|
||||
inserted between each element. `Intersperse` conforms to `Collection`,
|
||||
`BidirectionalCollection`, `RandomAccessCollection`, `LazySequenceProtocol` and
|
||||
`LazyCollectionProtocol` when the base sequence conforms to those respective
|
||||
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
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
# Joined
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Joined.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/JoinedTests.swift)]
|
||||
|
||||
Concatenate a sequence of sequences, inserting a separator between each element.
|
||||
|
||||
The separator can be either a single element or a sequence of elements, and it
|
||||
can optionally depend on the sequences right before and after it by returning it
|
||||
from a closure:
|
||||
|
||||
```swift
|
||||
for number in [[1], [2, 3], [4, 5, 6]].joined(by: 100) {
|
||||
print(number)
|
||||
}
|
||||
// 1, 100, 2, 3, 100, 4, 5, 6
|
||||
|
||||
for number in [[10], [20, 30], [40, 50, 60]].joined(by: { [$0.count, $1.count] }) {
|
||||
print(number)
|
||||
}
|
||||
// 10, 1, 2, 20, 30, 2, 3, 40, 50, 60
|
||||
```
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The versions that take a closure are executed eagerly and are defined on
|
||||
`Sequence`:
|
||||
|
||||
```swift
|
||||
extension Sequence where Element: Sequence {
|
||||
public func joined(
|
||||
by separator: (Element, Element) throws -> Element.Element
|
||||
) rethrows -> [Element.Element]
|
||||
|
||||
public func joined<Separator>(
|
||||
by separator: (Element, Element) throws -> Separator
|
||||
) rethrows -> [Element.Element]
|
||||
where Separator: Sequence, Separator.Element == Element.Element
|
||||
}
|
||||
```
|
||||
|
||||
The versions that do not take a closure are defined on both `Sequence` and
|
||||
`Collection` because the resulting collections need to precompute their start
|
||||
index to ensure O(1) access:
|
||||
|
||||
```swift
|
||||
extension Sequence where Element: Sequence {
|
||||
public func joined(by separator: Element.Element)
|
||||
-> JoinedBySequence<Self, CollectionOfOne<Element.Element>>
|
||||
|
||||
public func joined<Separator>(
|
||||
by separator: Separator
|
||||
) -> JoinedBySequence<Self, Separator>
|
||||
where Separator: Collection, Separator.Element == Element.Element
|
||||
}
|
||||
|
||||
extension Collection where Element: Sequence {
|
||||
public func joined(by separator: Element.Element)
|
||||
-> JoinedByCollection<Self, CollectionOfOne<Element.Element>>
|
||||
|
||||
public func joined<Separator>(
|
||||
by separator: Separator
|
||||
) -> JoinedByCollection<Self, Separator>
|
||||
where Separator: Collection, Separator.Element == Element.Element
|
||||
}
|
||||
```
|
||||
|
||||
Note that the sequence separator of the closure-less version defined on
|
||||
`Sequence` is required to be a `Collection`, because a plain `Sequence` cannot in
|
||||
general be iterated over multiple times.
|
||||
|
||||
The closure-based versions also have lazy variants that are defined on both
|
||||
lazy sequences and collections for the same reason as explained above:
|
||||
|
||||
```swift
|
||||
extension LazySequenceProtocol where Element: Sequence {
|
||||
public func joined(
|
||||
by separator: @escaping (Element, Element) -> Element.Element
|
||||
) -> JoinedByClosureSequence<Self, CollectionOfOne<Element.Element>>
|
||||
|
||||
public func joined<Separator>(
|
||||
by separator: @escaping (Element, Element) -> Separator
|
||||
) -> JoinedByClosureSequence<Self, Separator>
|
||||
}
|
||||
|
||||
extension LazySequenceProtocol where Self: Collection, Element: Collection {
|
||||
public func joined(
|
||||
by separator: @escaping (Element, Element) -> Element.Element
|
||||
) -> JoinedByClosureCollection<Self, CollectionOfOne<Element.Element>>
|
||||
|
||||
public func joined<Separator>(
|
||||
by separator: @escaping (Element, Element) -> Separator
|
||||
) -> JoinedByClosureCollection<Self, Separator>
|
||||
}
|
||||
```
|
||||
|
||||
`JoinedBySequence`, `JoinedByClosureSequence`, `JoinedByCollection`, and
|
||||
`JoinedByClosureCollection` conform to `LazySequenceProtocol` when the base
|
||||
sequence conforms. `JoinedByCollection` and `JoinedByClosureCollection` also
|
||||
conform to `BidirectionalCollection` when the base collection conforms.
|
||||
@@ -1,80 +0,0 @@
|
||||
# LazySplit
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/LazySplit.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/LazySplitTests.swift)]
|
||||
|
||||
Lazily-evaluating versions of
|
||||
[`split(maxSplits:omittingEmptySubsequences:whereSeparator:)`](https://developer.apple.com/documentation/swift/sequence/3128814-split)
|
||||
and [`split(separator:maxSplits:omittingEmptySubsequences:)`](https://developer.apple.com/documentation/swift/sequence/3128818-split),
|
||||
performing the same operation as their counterparts defined on
|
||||
`Sequence` and `Collection`, are added to `LazySequence` and
|
||||
`LazyCollection`. The `LazyCollection` methods allow splitting a
|
||||
collection without allocating additional storage on the heap.
|
||||
|
||||
```swift
|
||||
// Splitting a lazy sequence.
|
||||
let numbers = stride(from: 1, through: 16, by: 1)
|
||||
for subsequence in numbers.lazy.split(
|
||||
whereSeparator: { $0 % 3 == 0 || $0 % 5 == 0 }
|
||||
) {
|
||||
print(subsequence)
|
||||
}
|
||||
/* Prints:
|
||||
[1, 2]
|
||||
[4]
|
||||
[7, 8]
|
||||
[11]
|
||||
[13, 14]
|
||||
[16]
|
||||
*/
|
||||
|
||||
// Splitting a lazy collection.
|
||||
let line = "BLANCHE: I don't want realism. I want magic!"
|
||||
for subsequence in line.lazy.split(separator: " ") {
|
||||
print(subsequence)
|
||||
}
|
||||
/* Prints
|
||||
BLANCHE:
|
||||
I
|
||||
don't
|
||||
want
|
||||
realism.
|
||||
I
|
||||
want
|
||||
magic!
|
||||
*/
|
||||
```
|
||||
|
||||
## Detailed Design
|
||||
|
||||
`LazySequence` and `LazyCollection` are each extended with
|
||||
`split(maxSplits:omittingEmptySubsequences:whereSeparator:)` and
|
||||
`split(separator:maxSplits:omittingEmptySubsequences:)`.
|
||||
|
||||
The `LazySequence` versions of those methods return an instance of
|
||||
`LazySplitSequence`. The `LazyCollection` versions return an instance of
|
||||
`LazySplitCollection`.
|
||||
|
||||
`LazySplitSequence` wraps the sequence to be split, and provides an
|
||||
iterator whose `next` method returns a newly-allocated array containing
|
||||
the elements of each subsequence in the split sequence in turn.
|
||||
|
||||
`LazySplitCollection` wraps the collection to be split. Its `Index`
|
||||
wraps a range of base collection indices. `startIndex` is computed at
|
||||
initialization. Subscripting a `LazySplitCollection` instance returns
|
||||
the slice of the original collection which is the subsequence of the
|
||||
split collection at the given index's position.
|
||||
|
||||
### Complexity
|
||||
|
||||
Iterating a `LazySplitSequence` instance is O(_n_) in time and space,
|
||||
since each subsequence returned is a newly-allocated array.
|
||||
|
||||
Iterating a `LazySplitCollection` instance is O(_n_) in time and O(1) in
|
||||
space, since each subsequence returned is a slice of the base
|
||||
collection. Since `startIndex` is computed at initialization, some or
|
||||
all of the time cost may be paid at initialization. For example, if the
|
||||
base collection contains no elements determined to be separators, it
|
||||
will be iterated entirely on initialization of the split collection, and
|
||||
all subsequent operations on the split collection, such as
|
||||
`index(after:)`, will have complexity O(1).
|
||||
+59
-8
@@ -1,11 +1,15 @@
|
||||
# Min/Max with Count
|
||||
# Minima and/or Maxima
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/MinMax.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/MinMaxTests.swift)]
|
||||
|
||||
Returns the smallest or largest elements of this collection, sorted by a predicate or in the order defined by `Comparable` conformance.
|
||||
Returns the smallest or largest elements of this collection, sorted by a
|
||||
predicate or in the order defined by `Comparable` conformance.
|
||||
|
||||
If you need to sort a collection but only need access to a prefix or suffix of the sorted elements, using these methods can give you a performance boost over sorting the entire collection. The order of equal elements is guaranteed to be preserved.
|
||||
If you need to sort a collection but only need access to a prefix or suffix of
|
||||
the sorted elements, using these methods can give you a performance boost over
|
||||
sorting the entire collection. The order of equal elements is guaranteed to be
|
||||
preserved.
|
||||
|
||||
```swift
|
||||
let numbers = [7, 1, 6, 2, 8, 3, 9]
|
||||
@@ -13,6 +17,20 @@ let smallestThree = numbers.min(count: 3, sortedBy: <)
|
||||
// [1, 2, 3]
|
||||
```
|
||||
|
||||
Return the smallest and largest elements of this sequence, determined by a
|
||||
predicate or in the order defined by `Comparable` conformance.
|
||||
|
||||
If you need both the minimum and maximum values of a collection, using these
|
||||
methods can give you a performance boost over running the `min` method followed
|
||||
by the `max` method. Plus they work with single-pass sequences.
|
||||
|
||||
```swift
|
||||
let numbers = [7, 1, 6, 2, 8, 3, 9]
|
||||
if let (smallest, largest) = numbers.minAndMax(by: <) {
|
||||
// Work with 1 and 9....
|
||||
}
|
||||
```
|
||||
|
||||
## Detailed Design
|
||||
|
||||
This adds the `Collection` methods shown below:
|
||||
@@ -31,7 +49,18 @@ extension Collection {
|
||||
}
|
||||
```
|
||||
|
||||
Additionally, versions of these methods for `Comparable` types are also provided:
|
||||
And the `Sequence` method:
|
||||
|
||||
```swift
|
||||
extension Sequence {
|
||||
public func minAndMax(
|
||||
by areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows -> (min: Element, max: Element)?
|
||||
}
|
||||
```
|
||||
|
||||
Additionally, versions of these methods for `Comparable` types are also
|
||||
provided:
|
||||
|
||||
```swift
|
||||
extension Collection where Element: Comparable {
|
||||
@@ -39,20 +68,42 @@ extension Collection where Element: Comparable {
|
||||
|
||||
public func max(count: Int) -> [Element]
|
||||
}
|
||||
|
||||
extension Sequence where Element: Comparable {
|
||||
public func minAndMax() -> (min: Element, max: Element)?
|
||||
}
|
||||
```
|
||||
|
||||
### Complexity
|
||||
|
||||
The algorithm used is based on [Soroush Khanlou's research on this matter](https://khanlou.com/2018/12/analyzing-complexity/). The total complexity is `O(k log k + nk)`, which will result in a runtime close to `O(n)` if *k* is a small amount. If *k* is a large amount (more than 10% of the collection), we fall back to sorting the entire array. Realistically, this means the worst case is actually `O(n log n)`.
|
||||
The algorithm used for minimal- or maximal-ordered subsets is based on
|
||||
[Soroush Khanlou's research on this matter](https://khanlou.com/2018/12/analyzing-complexity/).
|
||||
The total complexity is `O(k log k + nk)`, which will result in a runtime close
|
||||
to `O(n)` if *k* is a small amount. If *k* is a large amount (more than 10% of
|
||||
the collection), we fall back to sorting the entire array. Realistically, this
|
||||
means the worst case is actually `O(n log n)`.
|
||||
|
||||
Here are some benchmarks we made that demonstrates how this implementation (SmallestM) behaves when *k* increases (before implementing the fallback):
|
||||
Here are some benchmarks we made that demonstrates how this implementation
|
||||
(SmallestM) behaves when *k* increases (before implementing the fallback):
|
||||
|
||||

|
||||

|
||||
|
||||
The algorithm used for simultaneous minimum and maximum is slightly optimized.
|
||||
At each iteration, two elements are read, their relative order is determined,
|
||||
then each is compared against exactly one of the current extrema for potential
|
||||
replacement. When a comparison predicate has to analyze every component of both
|
||||
operands, the optimized algorithm isn't much faster than the straightforward
|
||||
approach. But when a predicate only needs to compare a small part of each
|
||||
instance, the optimization shines through.
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
**C++:** The `<algorithm>` library defines a `partial_sort` function where the entire array is returned using a partial heap sort.
|
||||
**C++:** The `<algorithm>` library defines a `partial_sort` function where the
|
||||
entire array is returned using a partial heap sort. It also defines a
|
||||
`minmax_element` function that scans a range for its minimal and maximal
|
||||
elements.
|
||||
|
||||
**Python:** Defines a `heapq` priority queue that can be used to manually achieve the same result.
|
||||
**Python:** Defines a `heapq` priority queue that can be used to manually
|
||||
achieve the same result.
|
||||
|
||||
+24
-1
@@ -42,6 +42,20 @@ let p = numbers.partitioningIndex(where: { $0.isMultiple(of: 20) })
|
||||
// numbers[p...] = [20, 40, 60]
|
||||
```
|
||||
|
||||
The standard library’s existing `filter(_:)` method provides functionality to
|
||||
get the elements that do match a given predicate. `partitioned(by:)` returns
|
||||
both the elements that match the predicate as well as those that don’t, as a
|
||||
tuple.
|
||||
|
||||
```swift
|
||||
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
|
||||
let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })
|
||||
print(longNames)
|
||||
// Prints "["Vivien", "Marlon"]"
|
||||
print(shortNames)
|
||||
// Prints "["Kim", "Karl"]"
|
||||
```
|
||||
|
||||
## Detailed Design
|
||||
|
||||
All mutating methods are declared as extensions to `MutableCollection`.
|
||||
@@ -69,11 +83,17 @@ extension Collection {
|
||||
where belongsInSecondPartition: (Element) throws -> Bool
|
||||
) rethrows -> Index
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
public func partitioned(
|
||||
by predicate: (Element) throws -> Bool
|
||||
) rethrows -> (falseElements: [Element], trueElements: [Element])
|
||||
}
|
||||
```
|
||||
|
||||
### Complexity
|
||||
|
||||
The existing partition is an O(_n_) operations, where _n_ is the length of the
|
||||
The existing partition is an O(_n_) operation, where _n_ is the length of the
|
||||
range to be partitioned, while the stable partition is O(_n_ log _n_). Both
|
||||
partitions have algorithms with improved performance for bidirectional
|
||||
collections, so it would be ideal for those to be customization points were they
|
||||
@@ -82,6 +102,9 @@ to eventually land in the standard library.
|
||||
`partitioningIndex(where:)` is a slight generalization of a binary search, and
|
||||
is an O(log _n_) operation for random-access collections; O(_n_) otherwise.
|
||||
|
||||
`partitioned(by:)` is an O(_n_) operation, where _n_ is the number of elements
|
||||
in the original sequence.
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
**C++:** The `<algorithm>` library defines `partition`, `stable_partition`, and
|
||||
|
||||
+15
-13
@@ -98,19 +98,20 @@ for perm in numbers.permutations(ofCount: 0...) {
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The `permutations(ofCount:)` and `uniquePermutations(ofCount:)` methods are declared as `Collection` extensions,
|
||||
and return `Permutations` and `UniquePermutations` instances, respectively:
|
||||
The `permutations(ofCount:)` and `uniquePermutations(ofCount:)` methods are
|
||||
declared as `Collection` extensions, and return `PermutationsSequence` and
|
||||
`UniquePermutationsSequence` instances, respectively:
|
||||
|
||||
```swift
|
||||
extension Collection {
|
||||
public func permutations(ofCount k: Int? = nil) -> Permutations<Self>
|
||||
public func permutations<R>(ofCount kRange: R) -> Permutations<Self>
|
||||
public func permutations(ofCount k: Int? = nil) -> PermutationsSequence<Self>
|
||||
public func permutations<R>(ofCount kRange: R) -> PermutationsSequence<Self>
|
||||
where R: RangeExpression, R.Bound == Int
|
||||
}
|
||||
|
||||
extension Collection where Element: Hashable {
|
||||
public func uniquePermutations(ofCount k: Int? = nil) -> UniquePermutations<Self>
|
||||
public func uniquePermutations<R>(ofCount kRange: R) -> UniquePermutations<Self>
|
||||
public func uniquePermutations(ofCount k: Int? = nil) -> UniquePermutationsSequence<Self>
|
||||
public func uniquePermutations<R>(ofCount kRange: R) -> UniquePermutationsSequence<Self>
|
||||
where R: RangeExpression, R.Bound == Int
|
||||
}
|
||||
```
|
||||
@@ -119,18 +120,19 @@ Since both result types need to store an array of the collection’s
|
||||
indices and mutate the array to generate each permutation, they only
|
||||
have `Sequence` conformance. Adding `Collection` conformance would require
|
||||
storing the array in the index type, which would in turn lead to copying the
|
||||
array at every index advancement. The `Permutations` type
|
||||
conforms to `LazySequenceProtocol` when its base type conforms.
|
||||
array at every index advancement. The `PermutationsSequence` and
|
||||
`UniquePermutationsSequence` types conforms to `LazySequenceProtocol` when their
|
||||
base type conforms.
|
||||
|
||||
### Complexity
|
||||
|
||||
Calling `permutations()` is an O(1) operation. Creating the iterator for a
|
||||
`Permutations` instance and each call to `Permutations.Iterator.next()` is an
|
||||
O(_n_) operation.
|
||||
`PermutationsSequence` instance and each call to
|
||||
`PermutationsSequence.Iterator.next()` is an O(_n_) operation.
|
||||
|
||||
Calling `uniquePermutations()` is an O(_n_) operation, because it preprocesses the
|
||||
collection to find duplicate elements. Creating the iterator for and each call to
|
||||
`next()` is also an O(_n_) operation.
|
||||
Calling `uniquePermutations()` is an O(_n_) operation, because it preprocesses
|
||||
the collection to find duplicate elements. Creating the iterator for and each
|
||||
call to `next()` is also an O(_n_) operation.
|
||||
|
||||
### Naming
|
||||
|
||||
|
||||
+7
-7
@@ -25,26 +25,26 @@ When either collection is empty, the resulting wrapper collection is also empty.
|
||||
## Detailed Design
|
||||
|
||||
The `product` function takes (at minimum) a sequence and a collection and
|
||||
returns a `Product2` type:
|
||||
returns a `Product2Sequence` type:
|
||||
|
||||
```swift
|
||||
public func product<Base1: Sequence, Base2: Collection>(
|
||||
_ s1: Base1, _ s2: Base2
|
||||
) -> Product2<Base1, Base2>
|
||||
) -> Product2Sequence<Base1, Base2>
|
||||
```
|
||||
|
||||
We require `Collection` conformance for `Base2`, since it needs to be iterated
|
||||
over multiple times. `Base1`, by contrast, is only iterated over a single time,
|
||||
so it can be a sequence.
|
||||
|
||||
The `Product2` type wraps the base sequence and collection, and acts as a
|
||||
sequence in the base case, upgrading to a collection, a bidirectional
|
||||
The `Product2Sequence` type wraps the base sequence and collection, and acts as
|
||||
a sequence in the base case, upgrading to a collection, a bidirectional
|
||||
collection, and a random-access collection when both base collections have those
|
||||
conformances.
|
||||
|
||||
We don't provide higher arities (like `Product3`, `Product4`, etc.) at this
|
||||
time to match the standard library's `Zip2` type. Users can compose multiple
|
||||
calls to `product` if they would like higher arities.
|
||||
We don't provide higher arities (like `Product3Sequence`, `Product4Sequence`,
|
||||
etc.) at this time to match the standard library's `Zip2Sequence` type. Users
|
||||
can compose multiple calls to `product` if they would like higher arities.
|
||||
|
||||
### Complexity
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ source.randomSample(count: 4)
|
||||
// e.g. [30, 10, 70, 50]
|
||||
source.randomStableSample(count: 4)
|
||||
// e.g. [20, 30, 80, 100]
|
||||
//
|
||||
|
||||
var rng = SplitMix64(seed: 0)
|
||||
source.randomSample(count: 4, using: &rng)
|
||||
```
|
||||
@@ -146,4 +146,4 @@ performance characteristics as the collection itself, so a user can call
|
||||
The stable version of sampling could theoretically return a lazy wrapper
|
||||
instead of eagerly creating the sample. However, this isn’t well-motivated and
|
||||
poses some challenges, such as needing to store a copy of the random generator
|
||||
and potentially needing to cache the randomly-generated values.
|
||||
and potentially needing to cache the randomly-generated values.
|
||||
+27
-30
@@ -3,9 +3,8 @@
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Reductions.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/ReductionsTests.swift)]
|
||||
|
||||
Produces a sequence of values.
|
||||
|
||||
This has the behaviour of reduce, but also returns all intermediate results.
|
||||
Produces all the intermediate results of reducing a sequence's elements using a
|
||||
closure.
|
||||
|
||||
```swift
|
||||
let exclusiveRunningTotal = (1...5).reductions(0, +)
|
||||
@@ -28,39 +27,37 @@ sequence and another trio are added to `Sequence` which are eagerly evaluated.
|
||||
|
||||
```swift
|
||||
extension LazySequenceProtocol {
|
||||
public func reductions<Result>(
|
||||
_ initial: Result,
|
||||
_ transform: @escaping (Result, Element) -> Result
|
||||
) -> ExclusiveReductionsSequence<Result, Self>
|
||||
|
||||
public func reductions<Result>(
|
||||
_ initial: Result,
|
||||
_ transform: @escaping (Result, Element) -> Result
|
||||
) -> ExclusiveReductions<Result, Self>
|
||||
public func reductions<Result>(
|
||||
into initial: Result,
|
||||
_ transform: @escaping (inout Result, Element) -> Void
|
||||
) -> ExclusiveReductionsSequence<Result, Self>
|
||||
|
||||
public func reductions<Result>(
|
||||
into initial: Result,
|
||||
_ transform: @escaping (inout Result, Element) -> Void
|
||||
) -> ExclusiveReductions<Result, Self>
|
||||
|
||||
public func reductions(
|
||||
_ transform: @escaping (Element, Element) -> Element
|
||||
) -> InclusiveReductions<Self>
|
||||
public func reductions(
|
||||
_ transform: @escaping (Element, Element) -> Element
|
||||
) -> InclusiveReductionsSequence<Self>
|
||||
}
|
||||
```
|
||||
|
||||
```swift
|
||||
extension Sequence {
|
||||
public func reductions<Result>(
|
||||
_ initial: Result,
|
||||
_ transform: (Result, Element) throws -> Result
|
||||
) rethrows -> [Result]
|
||||
|
||||
public func reductions<Result>(
|
||||
_ initial: Result,
|
||||
_ transform: (Result, Element) throws -> Result
|
||||
) rethrows -> [Result]
|
||||
public func reductions<Result>(
|
||||
into initial: Result,
|
||||
_ transform: (inout Result, Element) throws -> Void
|
||||
) rethrows -> [Result]
|
||||
|
||||
public func reductions<Result>(
|
||||
into initial: Result,
|
||||
_ transform: (inout Result, Element) throws -> Void
|
||||
) rethrows -> [Result]
|
||||
|
||||
public func reductions(
|
||||
_ transform: (Element, Element) throws -> Element
|
||||
) rethrows -> [Element]
|
||||
public func reductions(
|
||||
_ transform: (Element, Element) throws -> Element
|
||||
) rethrows -> [Element]
|
||||
}
|
||||
```
|
||||
|
||||
@@ -104,7 +101,7 @@ takes an initial value to use for the first element in the returned sequence,
|
||||
and another which uses the first value of the base sequence as the initial
|
||||
value. C++ calls these variants exclusive and inclusive respectively and so
|
||||
these terms carry through as the name for the lazy sequences;
|
||||
`ExclusiveReductions` and `InclusiveReductions`.
|
||||
`ExclusiveReductionsSequence` and `InclusiveReductionsSequence`.
|
||||
|
||||
[SE-0045]: https://forums.swift.org/t/review-se-0045-add-scan-prefix-while-drop-while-and-iterate-to-the-stdlib/2382
|
||||
[Issue 25]: https://github.com/apple/swift-algorithms/issues/25
|
||||
@@ -112,7 +109,7 @@ these terms carry through as the name for the lazy sequences;
|
||||
[David Rönnqvist]: https://forums.swift.org/t/review-se-0045-add-scan-prefix-while-drop-while-and-iterate-to-the-stdlib/2382/8
|
||||
[Kyle Macomber]: https://github.com/apple/swift-algorithms/issues/25#issuecomment-709317894
|
||||
|
||||
### Comparison with other langauges
|
||||
### Comparison with other languages
|
||||
|
||||
**C++:** As of C++17, the `<algorithm>` library includes both
|
||||
[`exclusive_scan`][C++ Exclusive] and [`inclusive_scan`][C++ Inclusive]
|
||||
@@ -124,7 +121,7 @@ functions.
|
||||
`Traversable` type, which is akin to Swift's `Sequence`.
|
||||
|
||||
**Python:** Python’s `itertools` includes an `accumulate` method. In version
|
||||
3.3, a function paramenter was added. Version 3.8 added the optional initial
|
||||
3.3, a function parameter was added. Version 3.8 added the optional initial
|
||||
parameter.
|
||||
|
||||
**[Rust][Rust]:** Rust provides a `scan` function.
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 74 KiB After Width: | Height: | Size: 64 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 77 KiB After Width: | Height: | Size: 69 KiB |
@@ -0,0 +1,79 @@
|
||||
# Split
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Split.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/SplitTests.swift)]
|
||||
|
||||
Lazily-evaluating versions of
|
||||
[`split(maxSplits:omittingEmptySubsequences:whereSeparator:)`](https://developer.apple.com/documentation/swift/sequence/3128814-split)
|
||||
and [`split(separator:maxSplits:omittingEmptySubsequences:)`](https://developer.apple.com/documentation/swift/sequence/3128818-split),
|
||||
performing the same operation as their counterparts defined on
|
||||
`Sequence` and `Collection`, are added to `LazySequence` and
|
||||
`LazyCollection`. The `LazyCollection` methods allow splitting a
|
||||
collection without allocating additional storage on the heap.
|
||||
|
||||
```swift
|
||||
// Splitting a lazy sequence.
|
||||
let numbers = stride(from: 1, through: 16, by: 1)
|
||||
for subsequence in numbers.lazy.split(
|
||||
whereSeparator: { $0 % 3 == 0 || $0 % 5 == 0 }
|
||||
) {
|
||||
print(subsequence)
|
||||
}
|
||||
/* Prints:
|
||||
[1, 2]
|
||||
[4]
|
||||
[7, 8]
|
||||
[11]
|
||||
[13, 14]
|
||||
[16]
|
||||
*/
|
||||
|
||||
// Splitting a lazy collection.
|
||||
let line = "BLANCHE: I don't want realism. I want magic!"
|
||||
for subsequence in line.lazy.split(separator: " ") {
|
||||
print(subsequence)
|
||||
}
|
||||
/* Prints
|
||||
BLANCHE:
|
||||
I
|
||||
don't
|
||||
want
|
||||
realism.
|
||||
I
|
||||
want
|
||||
magic!
|
||||
*/
|
||||
```
|
||||
|
||||
## Detailed Design
|
||||
|
||||
`LazySequence` and `LazyCollection` are each extended with
|
||||
`split(maxSplits:omittingEmptySubsequences:whereSeparator:)` and
|
||||
`split(separator:maxSplits:omittingEmptySubsequences:)`.
|
||||
|
||||
The `LazySequence` versions of those methods return an instance of
|
||||
`SplitSequence`. The `LazyCollection` versions return an instance of
|
||||
`SplitCollection`.
|
||||
|
||||
`SplitSequence` wraps the sequence to be split, and provides an iterator whose
|
||||
`next` method returns a newly-allocated array containing the elements of each
|
||||
subsequence in the split sequence in turn.
|
||||
|
||||
`SplitCollection` wraps the collection to be split. Its `Index` wraps a range of
|
||||
base collection indices. `startIndex` is computed at initialization.
|
||||
Subscripting a `SplitCollection` instance returns the slice of the original
|
||||
collection which is the subsequence of the split collection at the given index's
|
||||
position.
|
||||
|
||||
### Complexity
|
||||
|
||||
Iterating a `SplitSequence` instance is O(_n_) in time and space, since each
|
||||
subsequence returned is a newly-allocated array.
|
||||
|
||||
Iterating a `SplitCollection` instance is O(_n_) in time and O(1) in space,
|
||||
since each subsequence returned is a slice of the base collection. Since
|
||||
`startIndex` is computed at initialization, some or all of the time cost may be
|
||||
paid at initialization. For example, if the base collection contains no elements
|
||||
determined to be separators, it will be iterated entirely on initialization of
|
||||
the split collection, and all subsequent operations on the split collection,
|
||||
such as `index(after:)`, will have complexity O(1).
|
||||
+25
-18
@@ -3,7 +3,7 @@
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Stride.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/StrideTests.swift)]
|
||||
|
||||
A type that steps over sequence elements by the specified amount.
|
||||
Step over the elements of a sequence elements by a specified amount.
|
||||
|
||||
This is available through the `striding(by:)` method on any `Sequence`.
|
||||
|
||||
@@ -11,33 +11,39 @@ This is available through the `striding(by:)` method on any `Sequence`.
|
||||
(0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10]
|
||||
```
|
||||
|
||||
If the stride is larger than the count, the resulting wrapper only contains the
|
||||
first element.
|
||||
If the stride is larger than the length of the sequence, the resulting wrapper
|
||||
only contains the first element.
|
||||
|
||||
The stride amount must be a positive value.
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The `striding(by:)` method is declared as a `Sequence` extension, and returns a
|
||||
`Stride` type:
|
||||
The `striding(by:)` method is declared in extension of both `Sequence` and
|
||||
`Collection`:
|
||||
|
||||
```swift
|
||||
extension Sequence {
|
||||
public func striding(by step: Int) -> Stride<Self>
|
||||
public func striding(by step: Int) -> StridingSequence<Self>
|
||||
}
|
||||
|
||||
extension Collection {
|
||||
public func striding(by step: Int) -> StridingCollection<Self>
|
||||
}
|
||||
```
|
||||
|
||||
A custom `Index` type is defined so that it's not possible to get confused when trying
|
||||
to access an index of the stride collection.
|
||||
The reason for this distinction is subtle. The `StridingSequence.Iterator` type
|
||||
is unable to skip over multiple elements of the wrapped iterator at once since
|
||||
that's not part of `IteratorProtocol`'s interface. In order to efficiently
|
||||
stride over collections that provide a fast way of skipping multiple elements at
|
||||
once, the `StridingCollection` type was added which does not provide a custom
|
||||
`Iterator` type and therefore always strides over the underlying collection in
|
||||
the fastest way possible. See the related
|
||||
[GitHub issue](https://github.com/apple/swift-algorithms/issues/63) for more
|
||||
information.
|
||||
|
||||
```swift
|
||||
[0, 1, 2, 3, 4].striding(by: 2)[1] // == 1
|
||||
[0, 1, 2, 3, 4].striding(by: 2).map { $0 }[1] // == 2
|
||||
```
|
||||
|
||||
A careful thought was given to the composition of these strides by giving a custom
|
||||
implementation to `index(_:offsetBy:limitedBy)` which multiplies the offset by the
|
||||
stride amount.
|
||||
A careful thought was given to the composition of these strides by giving a
|
||||
custom implementation to `index(_:offsetBy:limitedBy)` which multiplies the
|
||||
offset by the stride amount.
|
||||
|
||||
```swift
|
||||
base.index(i.base, offsetBy: distance * stride, limitedBy: base.endIndex)
|
||||
@@ -52,8 +58,9 @@ The following two lines of code are equivalent, including performance:
|
||||
|
||||
### Complexity
|
||||
|
||||
The call to `striding(by: k)` is always O(_1_) and access to the next value in the stride
|
||||
is O(_1_) if the collection conforms to `RandomAccessCollection`, otherwise O(_k_).
|
||||
The call to `striding(by: k)` is always O(_1_) and access to the next value in
|
||||
the stride is O(_1_) if the collection conforms to `RandomAccessCollection`,
|
||||
otherwise O(_k_).
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
|
||||
+14
-14
@@ -3,37 +3,37 @@
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Suffix.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/SuffixTests.swift)]
|
||||
|
||||
This function returns a subsequence containing the elements from the end of the
|
||||
collection until predicate returns `false` and skipping the remaining elements.
|
||||
|
||||
This function returns a subsequence containing the elements from the end of the collection until predicate returns `false` and skipping the remaining elements.
|
||||
|
||||
This example uses `suffix(while: )` to iterate through collection of integers from the end until the predicate returns false, in this case when `$0 <= 5`
|
||||
This example uses `suffix(while: )` to iterate through collection of integers
|
||||
from the end until the predicate returns false, in this case when `$0 <= 5`
|
||||
```swift
|
||||
(0...10).suffix(while: { $0 > 5 } // == [6,7,8,9,10]
|
||||
```
|
||||
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The `suffix(while:)` function is added as a method on an extension of `BidirectionalCollection`.
|
||||
|
||||
The `suffix(while:)` function is added as a method on an extension of
|
||||
`BidirectionalCollection`.
|
||||
|
||||
```swift
|
||||
extension BidirectionalCollection {
|
||||
|
||||
public func suffix(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
|
||||
public func suffix(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
|
||||
}
|
||||
```
|
||||
|
||||
This method requires `BidirectionalCollection` for an efficient implementation which visits as few elements as possible. Swift's protocol allows for backward traversal of a collection as well as access to *last* property of a collection.
|
||||
This method requires `BidirectionalCollection` for an efficient implementation
|
||||
which visits as few elements as possible. Swift's protocol allows for backward
|
||||
traversal of a collection as well as access to *last* property of a collection.
|
||||
|
||||
### Complexity
|
||||
|
||||
Calling this method is O(*n*), where *n* is the length of the collection.
|
||||
|
||||
|
||||
### Naming
|
||||
|
||||
The function's name resembles that of an existing Swift function `prefix(while:)`, which performs same operation however in the forward direction of the collection. Hence, as this function traverses from the end of the collection, `suffix(while:)` is an appropriate name.
|
||||
|
||||
|
||||
|
||||
The function's name resembles that of an existing Swift function
|
||||
`prefix(while:)`, which performs same operation however in the forward direction
|
||||
of the collection. Hence, as this function traverses from the end of the
|
||||
collection, `suffix(while:)` is an appropriate name.
|
||||
+66
-31
@@ -3,10 +3,11 @@
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Trim.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/TrimTests.swift)]
|
||||
|
||||
Returns a `SubSequence` formed by discarding all elements at the start and end of the collection
|
||||
which satisfy the given predicate.
|
||||
Returns a `SubSequence` formed by discarding all elements at the start and end
|
||||
of the collection which satisfy the given predicate.
|
||||
|
||||
This example uses `trimming(while:)` to get a substring without the white space at the beginning and end of the string.
|
||||
This example uses `trimming(while:)` to get a substring without the white space
|
||||
at the beginning and end of the string.
|
||||
|
||||
```swift
|
||||
let myString = " hello, world "
|
||||
@@ -22,31 +23,56 @@ A new method is added to `BidirectionalCollection`:
|
||||
|
||||
```swift
|
||||
extension BidirectionalCollection {
|
||||
|
||||
public func trimming(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
|
||||
public func trimming(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
|
||||
}
|
||||
```
|
||||
|
||||
This method requires `BidirectionalCollection` for an efficient implementation which visits as few elements as possible.
|
||||
This method requires `BidirectionalCollection` for an efficient implementation
|
||||
which visits as few elements as possible.
|
||||
|
||||
A less-efficient implementation is _possible_ for any `Collection`, which would involve always traversing the
|
||||
entire collection. This implementation is not provided, as it would mean developers of generic algorithms who forget
|
||||
to add the `BidirectionalCollection` constraint will receive that inefficient implementation:
|
||||
A less-efficient implementation is _possible_ for any `Collection`, which would
|
||||
involve always traversing the entire collection. This implementation is not
|
||||
provided, as it would mean developers of generic algorithms who forget to add
|
||||
the `BidirectionalCollection` constraint will receive that inefficient
|
||||
implementation:
|
||||
|
||||
```swift
|
||||
func myAlgorithm<Input>(input: Input) where Input: Collection {
|
||||
|
||||
let trimmedInput = input.trimming(while: { ... }) // Uses least-efficient implementation.
|
||||
let trimmedInput = input.trimming(while: { ... }) // Uses least-efficient implementation.
|
||||
}
|
||||
|
||||
func myAlgorithm2<Input>(input: Input) where Input: BidirectionalCollection {
|
||||
|
||||
let trimmedInput = input.trimming(while: { ... }) // Uses most-efficient implementation.
|
||||
let trimmedInput = input.trimming(while: { ... }) // Uses most-efficient implementation.
|
||||
}
|
||||
```
|
||||
|
||||
Swift provides the `BidirectionalCollection` protocol for marking types which support reverse traversal,
|
||||
and generic types and algorithms which want to make use of that should add it to their constraints.
|
||||
Swift provides the `BidirectionalCollection` protocol for marking types which
|
||||
support reverse traversal, and generic types and algorithms which want to make
|
||||
use of that should add it to their constraints.
|
||||
|
||||
### >= 0.3.0
|
||||
|
||||
In `v0.3.0` new methods are added to allow discarding all the elements matching
|
||||
the predicate at the beginning (prefix) or at the ending (suffix) of the
|
||||
collection.
|
||||
- `trimmingSuffix(while:)` can only be run on collections conforming to the
|
||||
`BidirectionalCollection` protocol.
|
||||
- `trimmingPrefix(while:)` can be run also on collections conforming to the
|
||||
`Collection` protocol.
|
||||
|
||||
```swift
|
||||
let myString = " hello, world "
|
||||
print(myString.trimmingPrefix(while: \.isWhitespace)) // "hello, world "
|
||||
|
||||
print(myString.trimmingSuffix(while: \.isWhitespace)) // " hello, world"
|
||||
```
|
||||
Also mutating variants for all the methods already existing and the new ones are
|
||||
added.
|
||||
```swift
|
||||
var myString = " hello, world "
|
||||
myString.trim(while: \.isWhitespace)
|
||||
print(myString) // "hello, world"
|
||||
```
|
||||
|
||||
### Complexity
|
||||
|
||||
@@ -54,7 +80,8 @@ Calling this method is O(_n_).
|
||||
|
||||
### Naming
|
||||
|
||||
The name `trim` has precedent in other programming languages. Another popular alternative might be `strip`.
|
||||
The name `trim` has precedent in other programming languages. Another popular
|
||||
alternative might be `strip`.
|
||||
|
||||
| Example usage | Languages |
|
||||
|-|-|
|
||||
@@ -79,30 +106,38 @@ The name `trim` has precedent in other programming languages. Another popular al
|
||||
| TRIM(''string'') | SQL |
|
||||
| String.trim ''string'' | OCaml 4+ |
|
||||
|
||||
Note: This is an abbreviated list from Wikipedia. [Full table](https://en.wikipedia.org/wiki/Comparison_of_programming_languages_(string_functions)#trim)
|
||||
Note: This is an abbreviated list from Wikipedia.
|
||||
[Full table](https://en.wikipedia.org/wiki/Comparison_of_programming_languages_(string_functions)#trim)
|
||||
|
||||
The standard library includes a variety of methods which perform similar operations:
|
||||
The standard library includes a variety of methods which perform similar
|
||||
operations:
|
||||
|
||||
- Firstly, there are `dropFirst(Int)` and `dropLast(Int)`. These return slices but do not support user-defined predicates.
|
||||
If the collection's `count` is less than the number of elements to drop, they return an empty slice.
|
||||
- Secondly, there is `drop(while:)`, which also returns a slice and is equivalent to a 'left-trim' (trimming from the head but not the tail).
|
||||
If the entire collection is dropped, this method returns an empty slice.
|
||||
- Thirdly, there are `removeFirst(Int)` and `removeLast(Int)` which do not return slices and actually mutate the collection.
|
||||
If the collection's `count` is less than the number of elements to remove, this method triggers a runtime error.
|
||||
- Lastly, there are the `popFirst()` and `popLast()` methods, which work like `removeFirst()` and `removeLast()`,
|
||||
except they do not trigger a runtime error for empty collections.
|
||||
- Firstly, there are `dropFirst(Int)` and `dropLast(Int)`. These return slices
|
||||
but do not support user-defined predicates. If the collection's `count` is less
|
||||
than the number of elements to drop, they return an empty slice.
|
||||
- Secondly, there is `drop(while:)`, which also returns a slice and is
|
||||
equivalent to a 'left-trim' (trimming from the head but not the tail). If the
|
||||
entire collection is dropped, this method returns an empty slice.
|
||||
- Thirdly, there are `removeFirst(Int)` and `removeLast(Int)` which do not
|
||||
return slices and actually mutate the collection. If the collection's `count` is
|
||||
less than the number of elements to remove, this method triggers a runtime
|
||||
error.
|
||||
- Lastly, there are the `popFirst()` and `popLast()` methods, which work like
|
||||
`removeFirst()` and `removeLast()`, except they do not trigger a runtime error
|
||||
for empty collections.
|
||||
|
||||
The closest neighbours to this function would be the `drop` family of methods. Unfortunately, unlike `dropFirst(Int)`,
|
||||
the name `drop(while:)` does not specify which end(s) of the collection it operates on. Moreover, one could easily
|
||||
The closest neighbours to this function would be the `drop` family of methods.
|
||||
Unfortunately, unlike `dropFirst(Int)`,the name `drop(while:)` does not specify
|
||||
which end(s) of the collection it operates on. Moreover, one could easily
|
||||
mistake code such as:
|
||||
|
||||
```swift
|
||||
let result = myString.drop(while: \.isWhitespace)
|
||||
```
|
||||
|
||||
With a lazy filter that drops _all_ whitespace characters regardless of where they are in the string.
|
||||
Besides that, the root `trim` leads to clearer, more conscise code, which is more aligned with other programming
|
||||
languages:
|
||||
With a lazy filter that drops _all_ whitespace characters regardless of where
|
||||
they are in the string. Besides that, the root `trim` leads to clearer, more
|
||||
concise code, which is more aligned with other programming languages:
|
||||
|
||||
```swift
|
||||
// Does `result` contain the input, trimmed of certain elements?
|
||||
|
||||
+18
-12
@@ -5,38 +5,44 @@
|
||||
|
||||
Methods to strip repeated elements from a sequence or collection.
|
||||
|
||||
The `uniqued()` method returns an array, dropping duplicate elements
|
||||
from a sequence. The `uniqued(on:)` method does the same, using
|
||||
the result of the given closure to determine the "uniqueness" of each
|
||||
element.
|
||||
The `uniqued()` method returns a sequence, dropping duplicate elements from a
|
||||
sequence. The `uniqued(on:)` method does the same, using the result of the given
|
||||
closure to determine the "uniqueness" of each element.
|
||||
|
||||
```swift
|
||||
let numbers = [1, 2, 3, 3, 2, 3, 3, 2, 2, 2, 1]
|
||||
|
||||
let unique = numbers.uniqued()
|
||||
// unique == [1, 2, 3]
|
||||
// Array(unique) == [1, 2, 3]
|
||||
```
|
||||
|
||||
## Detailed Design
|
||||
|
||||
Both methods are available for sequences, with the simplest limited to
|
||||
when the element type conforms to `Hashable`. Both methods preserve
|
||||
the relative order of the elements.
|
||||
Both methods are available for sequences, with the simplest limited to when the
|
||||
element type conforms to `Hashable`. Both methods preserve the relative order of
|
||||
the elements. `uniqued(on:)` has a matching lazy version that is added to
|
||||
`LazySequenceProtocol`.
|
||||
|
||||
```swift
|
||||
extension Sequence where Element: Hashable {
|
||||
func uniqued() -> [Element]
|
||||
func uniqued() -> UniquedSequence<Self, Element>
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
func uniqued<T>(on: (Element) throws -> T) rethrows -> [Element]
|
||||
where T: Hashable
|
||||
func uniqued<Subject>(on projection: (Element) throws -> Subject) rethrows -> [Element]
|
||||
where Subject: Hashable
|
||||
}
|
||||
|
||||
extension LazySequenceProtocol {
|
||||
func uniqued<Subject>(on projection: @escaping (Element) -> Subject) -> UniquedSequence<Self, Subject>
|
||||
where Subject: Hashable
|
||||
}
|
||||
```
|
||||
|
||||
### Complexity
|
||||
|
||||
The `uniqued` methods are O(_n_) in both time and space complexity.
|
||||
The eager `uniqued(on:)` method is O(_n_) in both time and space complexity. The
|
||||
lazy versions are O(_1_).
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
|
||||
+12
-8
@@ -6,7 +6,9 @@
|
||||
Break a collection into overlapping subsequences where
|
||||
elements are slices from the original collection.
|
||||
|
||||
The `windows(ofCount:)` method takes a size as a parameter and returns a collection of subsequences. Each element of the returned collection is a successive overlapping slice of the given size.
|
||||
The `windows(ofCount:)` method takes a size as a parameter and returns a
|
||||
collection of subsequences. Each element of the returned collection is a
|
||||
successive overlapping slice of the given size.
|
||||
|
||||
```swift
|
||||
let swift = "swift"
|
||||
@@ -21,24 +23,26 @@ The `windows(ofCount:)` method is added as an extension `Collection` method:
|
||||
|
||||
```swift
|
||||
extension Collection {
|
||||
public func windows(ofCount count: Int) -> Windows<Self>
|
||||
public func windows(ofCount count: Int) -> WindowsOfCountCollection<Self>
|
||||
}
|
||||
```
|
||||
|
||||
If a size larger than the collection's length is specified, the returned collection is empty.
|
||||
If a size larger than the collection's length is specified, the returned
|
||||
collection is empty.
|
||||
|
||||
```swift
|
||||
[1, 2, 3].windows(ofCount: 5).isEmpty // true
|
||||
```
|
||||
|
||||
The resulting `Windows` type is a collection, with conditional conformance to the
|
||||
`BidirectionalCollection`, `RandomAccessCollection`, and
|
||||
`LazyCollectionProtocol` protocols when the base collection conforms.
|
||||
The resulting `WindowsOfCountCollection` type is a collection, with conditional
|
||||
conformance to the `BidirectionalCollection`, `RandomAccessCollection`, and
|
||||
`LazySequenceProtocol` protocols when the base collection conforms.
|
||||
|
||||
### Complexity
|
||||
|
||||
The call to `windows(ofCount: k)` is O(1) if the collection conforms to
|
||||
`RandomAccessCollection`, otherwise O(_k_). Access to each successive window is O(1).
|
||||
`RandomAccessCollection`, otherwise O(_k_). Access to each successive window is
|
||||
O(1).
|
||||
|
||||
### Naming
|
||||
|
||||
@@ -51,5 +55,5 @@ and `permutations(ofCount:)`.
|
||||
### Comparison with other languages
|
||||
|
||||
[rust](https://doc.rust-lang.org/std/slice/struct.Windows.html) has
|
||||
`std::slice::Windows` which is a method available on slices. It has the same
|
||||
`std::slice::Windows` which is a method available on slices. It has the same
|
||||
semantics as described here.
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
// swift-tools-version:5.1
|
||||
// swift-tools-version:5.4
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
@@ -20,7 +20,7 @@ let package = Package(
|
||||
targets: ["Algorithms"]),
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-numerics", from: "0.0.1"),
|
||||
.package(url: "https://github.com/apple/swift-numerics.git", from: "1.0.0"),
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
|
||||
@@ -20,15 +20,21 @@ Read more about the package, and the intent behind it, in the [announcement on s
|
||||
#### Combining collections
|
||||
|
||||
- [`chain(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Chain.md): Concatenates two collections with the same element type.
|
||||
- [`product(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Product.md): Iterates over all the pairs of two collections; equivalent to nested `for`-`in` loops.
|
||||
- [`cycled()`, `cycled(times:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Cycle.md): Repeats the elements of a collection forever or a set number of times.
|
||||
- [`joined(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Joined.md): Concatenate sequences of sequences, using an element or sequence as a separator, or using a closure to generate each separator.
|
||||
- [`product(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Product.md): Iterates over all the pairs of two collections; equivalent to nested `for`-`in` loops.
|
||||
|
||||
#### Subsetting operations
|
||||
|
||||
- [`compacted()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Compacted.md): Drops the `nil`s from a sequence or collection, unwrapping the remaining elements.
|
||||
- [`partitioned(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Partition.md): Returns the elements in a sequence or collection that do and do not match a given predicate.
|
||||
- [`randomSample(count:)`, `randomSample(count:using:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/RandomSampling.md): Randomly selects a specific number of elements from a collection.
|
||||
- [`randomStableSample(count:)`, `randomStableSample(count:using:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/RandomSampling.md): Randomly selects a specific number of elements from a collection, preserving their original relative order.
|
||||
- [`striding(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Stride.md): Returns every nth element of a collection.
|
||||
- [`suffix(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Suffix.md): Returns the suffix of a collection where all element pass a given predicate.
|
||||
- [`trimmingPrefix(while:)`, `trimmingSuffix(while)`, `trimming(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Trim.md): Returns a slice by trimming elements from a collection's start, end, or both. The mutating `trim...` methods trim a collection in place.
|
||||
- [`uniqued()`, `uniqued(on:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Unique.md): The unique elements of a collection, preserving their order.
|
||||
- [`minAndMax()`, `minAndMax(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/MinMax.md): Returns the smallest and largest elements of a sequence.
|
||||
|
||||
#### Partial sorting
|
||||
|
||||
@@ -36,13 +42,15 @@ Read more about the package, and the intent behind it, in the [announcement on s
|
||||
|
||||
#### Other useful operations
|
||||
|
||||
- [`adjacentPairs()`](https://github.com/apple/swift-algorithms/blob/main/Guides/AdjacentPairs.md): Lazily iterates over tuples of adjacent elements.
|
||||
- [`chunked(by:)`, `chunked(on:)`, `chunks(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Chunked.md): Eager and lazy operations that break a collection into chunks based on either a binary predicate or when the result of a projection changes or chunks of a given count.
|
||||
- [`firstNonNil(_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/FirstNonNil.md): Returns the first non-`nil` result from transforming a sequence's elements.
|
||||
- [`indexed()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Indexed.md): Iterate over tuples of a collection's indices and elements.
|
||||
- [`interspersed(with:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Intersperse.md): Place a value between every two elements of a sequence.
|
||||
- [`trimming(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Trim.md): Returns a slice by trimming elements from a collection's start and end.
|
||||
- [`partitioningIndex(where:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Partition.md): Returns the starting index of the partition of a collection that matches a predicate.
|
||||
- [`reductions(_:)`, `reductions(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Reductions.md): Returns all the intermediate states of reducing the elements of a sequence or collection.
|
||||
- [`split(maxSplits:omittingEmptySubsequences:whereSeparator)`, `split(separator:maxSplits:omittingEmptySubsequences)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Split.md): Lazy versions of the Standard Library's eager operations that split sequences and collections into subsequences separated by the specified separator element.
|
||||
- [`windows(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Windows.md): Breaks a collection into overlapping subsequences where elements are slices from the original collection.
|
||||
- [`striding(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Stride.md): Returns every nth element of a collection.
|
||||
- [`split(maxSplits:omittingEmptySubsequences:whereSeparator)`, `split(separator:maxSplits:omittingEmptySubsequences)`](https://github.com/apple/swift-algorithms/blob/main/Guides/LazySplit.md): Lazy versions of the Standard Library's eager operations that split sequences and collections into subsequences separated by the specified separator element.
|
||||
|
||||
## Adding Swift Algorithms as a Dependency
|
||||
|
||||
@@ -50,32 +58,25 @@ To use the `Algorithms` library in a SwiftPM project,
|
||||
add the following line to the dependencies in your `Package.swift` file:
|
||||
|
||||
```swift
|
||||
.package(url: "https://github.com/apple/swift-algorithms", from: "0.0.1"),
|
||||
.package(url: "https://github.com/apple/swift-algorithms", from: "1.0.0"),
|
||||
```
|
||||
|
||||
Because `Algorithms` is under active development,
|
||||
source-stability is only guaranteed within minor versions (e.g. between `0.0.3` and `0.0.4`).
|
||||
If you don't want potentially source-breaking package updates,
|
||||
use this dependency specification instead:
|
||||
Include `"Algorithms"` as a dependency for your executable target:
|
||||
|
||||
```swift
|
||||
.package(url: "https://github.com/apple/swift-algorithms", .upToNextMinor(from: "0.0.1")),
|
||||
.target(name: "<target>", dependencies: [
|
||||
.product(name: "Algorithms", package: "swift-algorithms"),
|
||||
]),
|
||||
```
|
||||
|
||||
Finally, include `"Algorithms"` as a dependency for your executable target:
|
||||
Finally, add `import Algorithms` to your source code.
|
||||
|
||||
```swift
|
||||
let package = Package(
|
||||
// name, platforms, products, etc.
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-algorithms", from: "0.0.1"),
|
||||
// other dependencies
|
||||
],
|
||||
targets: [
|
||||
.target(name: "<target>", dependencies: [
|
||||
.product(name: "Algorithms", package: "swift-algorithms"),
|
||||
]),
|
||||
// other targets
|
||||
]
|
||||
)
|
||||
```
|
||||
## Source Stability
|
||||
|
||||
The Swift Algorithms package is source stable; version numbers follow [Semantic Versioning](https://semver.org/). Source breaking changes to public API can only land in a new major version.
|
||||
|
||||
The public API of version 1.0 of the `swift-algorithms` package consists of non-underscored declarations that are marked `public` in the `Algorithms` module. Interfaces that aren't part of the public API may continue to change in any release, including patch releases.
|
||||
|
||||
Future minor versions of the package may introduce changes to these rules as needed.
|
||||
|
||||
We'd like this package to quickly embrace Swift language and toolchain improvements that are relevant to its mandate. Accordingly, from time to time, we expect that new versions of this package will require clients to upgrade to a more recent Swift toolchain release. Requiring a new Swift release will only require a minor version bump.
|
||||
@@ -0,0 +1,309 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Sequence {
|
||||
/// Returns a sequence of overlapping adjacent pairs of the elements of this
|
||||
/// sequence.
|
||||
///
|
||||
/// In the `AdjacentPairsSequence` returned by this method, the elements of
|
||||
/// the *i*th pair are the *i*th and *(i+1)*th elements of the underlying
|
||||
/// sequence. The following example uses the `adjacentPairs()` method to
|
||||
/// iterate over adjacent pairs of integers:
|
||||
///
|
||||
/// for pair in (1...).prefix(5).adjacentPairs() {
|
||||
/// print(pair)
|
||||
/// }
|
||||
/// // Prints "(1, 2)"
|
||||
/// // Prints "(2, 3)"
|
||||
/// // Prints "(3, 4)"
|
||||
/// // Prints "(4, 5)"
|
||||
///
|
||||
/// The resulting sequence is empty when called on an empty or single-element
|
||||
/// sequence.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func adjacentPairs() -> AdjacentPairsSequence<Self> {
|
||||
AdjacentPairsSequence(base: self)
|
||||
}
|
||||
}
|
||||
|
||||
extension Collection {
|
||||
/// Returns a collection of overlapping adjacent pairs of the elements of this
|
||||
/// collection.
|
||||
///
|
||||
/// In an `AdjacentPairsCollection`, the elements of the *i*th pair are the
|
||||
/// *i*th and *(i+1)*th elements of the underlying sequence. The following
|
||||
/// example uses the `adjacentPairs()` method to iterate over adjacent pairs
|
||||
/// of integers:
|
||||
///
|
||||
/// for pair in (1...5).adjacentPairs() {
|
||||
/// print(pair)
|
||||
/// }
|
||||
/// // Prints "(1, 2)"
|
||||
/// // Prints "(2, 3)"
|
||||
/// // Prints "(3, 4)"
|
||||
/// // Prints "(4, 5)"
|
||||
///
|
||||
/// The resulting collection is empty when called on an empty or
|
||||
/// single-element collection.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func adjacentPairs() -> AdjacentPairsCollection<Self> {
|
||||
AdjacentPairsCollection(base: self)
|
||||
}
|
||||
}
|
||||
|
||||
/// A sequence of adjacent pairs of elements built from an underlying sequence.
|
||||
///
|
||||
/// Use the `adjacentPairs()` method on a sequence to create an
|
||||
/// `AdjacentPairsSequence` instance.
|
||||
public struct AdjacentPairsSequence<Base: Sequence> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
/// Creates an instance that makes pairs of adjacent elements from `base`.
|
||||
@inlinable
|
||||
internal init(base: Base) {
|
||||
self.base = base
|
||||
}
|
||||
}
|
||||
|
||||
extension AdjacentPairsSequence {
|
||||
/// The iterator for an `AdjacentPairsSequence` or `AdjacentPairsCollection`
|
||||
/// instance.
|
||||
public struct Iterator {
|
||||
@usableFromInline
|
||||
internal var base: Base.Iterator
|
||||
|
||||
@usableFromInline
|
||||
internal var previousElement: Base.Element?
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base.Iterator) {
|
||||
self.base = base
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension AdjacentPairsSequence.Iterator: IteratorProtocol {
|
||||
public typealias Element = (Base.Element, Base.Element)
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Element? {
|
||||
if previousElement == nil {
|
||||
previousElement = base.next()
|
||||
}
|
||||
|
||||
guard let previous = previousElement, let next = base.next() else {
|
||||
return nil
|
||||
}
|
||||
|
||||
previousElement = next
|
||||
return (previous, next)
|
||||
}
|
||||
}
|
||||
|
||||
extension AdjacentPairsSequence: Sequence {
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(base: base.makeIterator())
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var underestimatedCount: Int {
|
||||
Swift.max(0, base.underestimatedCount - 1)
|
||||
}
|
||||
}
|
||||
|
||||
extension AdjacentPairsSequence: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
/// A collection of adjacent pairs of elements built from an underlying
|
||||
/// collection.
|
||||
///
|
||||
/// Use the `adjacentPairs()` method on a collection to create an
|
||||
/// `AdjacentPairsCollection` instance.
|
||||
public struct AdjacentPairsCollection<Base: Collection> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let secondBaseIndex: Base.Index
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base) {
|
||||
self.base = base
|
||||
self.secondBaseIndex = base.isEmpty
|
||||
? base.endIndex
|
||||
: base.index(after: base.startIndex)
|
||||
}
|
||||
}
|
||||
|
||||
extension AdjacentPairsCollection {
|
||||
/// A position in an `AdjacentPairsCollection` instance.
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal var first: Base.Index
|
||||
|
||||
@usableFromInline
|
||||
internal var second: Base.Index
|
||||
|
||||
@inlinable
|
||||
internal init(first: Base.Index, second: Base.Index) {
|
||||
self.first = first
|
||||
self.second = second
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func == (lhs: Index, rhs: Index) -> Bool {
|
||||
lhs.first == rhs.first
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
lhs.first < rhs.first
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension AdjacentPairsCollection: Collection {
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
Index(
|
||||
first: secondBaseIndex == base.endIndex ? base.endIndex : base.startIndex,
|
||||
second: secondBaseIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
Index(first: base.endIndex, second: base.endIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> (Base.Element, Base.Element) {
|
||||
(base[position.first], base[position.second])
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
precondition(i != endIndex, "Can't advance beyond endIndex")
|
||||
let next = base.index(after: i.second)
|
||||
return next == base.endIndex
|
||||
? endIndex
|
||||
: Index(first: i.second, second: next)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||
guard distance != 0 else { return i }
|
||||
|
||||
guard let result = distance > 0
|
||||
? offsetForward(i, by: distance, limitedBy: endIndex)
|
||||
: offsetBackward(i, by: -distance, limitedBy: startIndex)
|
||||
else { fatalError("Index out of bounds") }
|
||||
return result
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(
|
||||
_ i: Index, offsetBy distance: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
guard distance != 0 else { return i }
|
||||
guard limit != i else { return nil }
|
||||
|
||||
if distance > 0 {
|
||||
let limit = limit > i ? limit : endIndex
|
||||
return offsetForward(i, by: distance, limitedBy: limit)
|
||||
} else {
|
||||
let limit = limit < i ? limit : startIndex
|
||||
return offsetBackward(i, by: -distance, limitedBy: limit)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(
|
||||
_ i: Index, by distance: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance > 0)
|
||||
assert(limit > i)
|
||||
|
||||
guard let newFirst = base.index(i.second, offsetBy: distance - 1, limitedBy: limit.first),
|
||||
newFirst != base.endIndex
|
||||
else { return nil }
|
||||
let newSecond = base.index(after: newFirst)
|
||||
|
||||
precondition(newSecond <= base.endIndex, "Can't advance beyond endIndex")
|
||||
return newSecond == base.endIndex
|
||||
? endIndex
|
||||
: Index(first: newFirst, second: newSecond)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(
|
||||
_ i: Index, by distance: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance > 0)
|
||||
assert(limit < i)
|
||||
|
||||
let offset = i == endIndex ? 0 : 1
|
||||
guard let newSecond = base.index(
|
||||
i.first,
|
||||
offsetBy: -(distance - offset),
|
||||
limitedBy: limit.second)
|
||||
else { return nil }
|
||||
let newFirst = base.index(newSecond, offsetBy: -1)
|
||||
precondition(newFirst >= base.startIndex, "Can't move before startIndex")
|
||||
return Index(first: newFirst, second: newSecond)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
// While there's a 2-step gap between the `first` base index values in
|
||||
// `endIndex` and the penultimate index of this collection, the `second`
|
||||
// base index values are consistently one step apart throughout the
|
||||
// entire collection.
|
||||
base.distance(from: start.second, to: end.second)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var count: Int {
|
||||
Swift.max(0, base.count - 1)
|
||||
}
|
||||
}
|
||||
|
||||
extension AdjacentPairsCollection: BidirectionalCollection
|
||||
where Base: BidirectionalCollection
|
||||
{
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
precondition(i != startIndex, "Can't offset before startIndex")
|
||||
let second = i == endIndex
|
||||
? base.index(before: base.endIndex)
|
||||
: i.first
|
||||
let first = base.index(before: second)
|
||||
return Index(first: first, second: second)
|
||||
}
|
||||
}
|
||||
|
||||
extension AdjacentPairsCollection: RandomAccessCollection
|
||||
where Base: RandomAccessCollection {}
|
||||
|
||||
extension AdjacentPairsCollection: LazySequenceProtocol, LazyCollectionProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
extension AdjacentPairsCollection.Index: Hashable where Base.Index: Hashable {
|
||||
@inlinable
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(first)
|
||||
}
|
||||
}
|
||||
@@ -10,14 +10,16 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A concatenation of two sequences with the same element type.
|
||||
public struct Chain2<Base1: Sequence, Base2: Sequence>
|
||||
public struct Chain2Sequence<Base1: Sequence, Base2: Sequence>
|
||||
where Base1.Element == Base2.Element
|
||||
{
|
||||
/// The first sequence in this chain.
|
||||
public let base1: Base1
|
||||
@usableFromInline
|
||||
internal let base1: Base1
|
||||
|
||||
/// The second sequence in this chain.
|
||||
public let base2: Base2
|
||||
@usableFromInline
|
||||
internal let base2: Base2
|
||||
|
||||
@inlinable
|
||||
internal init(base1: Base1, base2: Base2) {
|
||||
@@ -26,8 +28,8 @@ public struct Chain2<Base1: Sequence, Base2: Sequence>
|
||||
}
|
||||
}
|
||||
|
||||
extension Chain2: Sequence {
|
||||
/// The iterator for a `Chain2` sequence.
|
||||
extension Chain2Sequence: Sequence {
|
||||
/// The iterator for a `Chain2Sequence` instance.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var iterator1: Base1.Iterator
|
||||
@@ -36,7 +38,7 @@ extension Chain2: Sequence {
|
||||
internal var iterator2: Base2.Iterator
|
||||
|
||||
@inlinable
|
||||
internal init(_ concatenation: Chain2) {
|
||||
internal init(_ concatenation: Chain2Sequence) {
|
||||
iterator1 = concatenation.base1.makeIterator()
|
||||
iterator2 = concatenation.base2.makeIterator()
|
||||
}
|
||||
@@ -53,8 +55,8 @@ extension Chain2: Sequence {
|
||||
}
|
||||
}
|
||||
|
||||
extension Chain2: Collection where Base1: Collection, Base2: Collection {
|
||||
/// A position in a `Chain2` collection.
|
||||
extension Chain2Sequence: Collection where Base1: Collection, Base2: Collection {
|
||||
/// A position in a `Chain2Sequence` instance.
|
||||
public struct Index: Comparable {
|
||||
// The internal index representation, which can either be an index of the
|
||||
// first collection or the second. The `endIndex` of the first collection
|
||||
@@ -62,7 +64,7 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
|
||||
// from the penultimate index of the first collection to the start of the
|
||||
// second.
|
||||
@usableFromInline
|
||||
internal enum Representation : Equatable {
|
||||
internal enum Representation: Equatable {
|
||||
case first(Base1.Index)
|
||||
case second(Base2.Index)
|
||||
}
|
||||
@@ -100,7 +102,7 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
|
||||
/// Converts an index of `Base1` to the corresponding `Index` by mapping
|
||||
/// `base1.endIndex` to `base2.startIndex`.
|
||||
@inlinable
|
||||
internal func convertIndex(_ i: Base1.Index) -> Index {
|
||||
internal func normalizeIndex(_ i: Base1.Index) -> Index {
|
||||
i == base1.endIndex ? Index(second: base2.startIndex) : Index(first: i)
|
||||
}
|
||||
|
||||
@@ -108,12 +110,12 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
|
||||
public var startIndex: Index {
|
||||
// if `base1` is empty, this will return `base2.startIndex` - if `base2` is
|
||||
// also empty, this will correctly equal `base2.endIndex`
|
||||
convertIndex(base1.startIndex)
|
||||
normalizeIndex(base1.startIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
return Index(second: base2.endIndex)
|
||||
Index(second: base2.endIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@@ -131,109 +133,116 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
|
||||
switch i.position {
|
||||
case let .first(i):
|
||||
assert(i != base1.endIndex)
|
||||
return convertIndex(base1.index(after: i))
|
||||
return normalizeIndex(base1.index(after: i))
|
||||
case let .second(i):
|
||||
return Index(second: base2.index(after: i))
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Index, offsetBy n: Int) -> Index {
|
||||
if n == 0 { return i }
|
||||
return n > 0
|
||||
? offsetForward(i, by: n, limitedBy: endIndex)!
|
||||
: offsetBackward(i, by: -n, limitedBy: startIndex)!
|
||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||
guard distance != 0 else { return i }
|
||||
|
||||
return distance > 0
|
||||
? offsetForward(i, by: distance)
|
||||
: offsetBackward(i, by: -distance)
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func index(
|
||||
_ i: Index,
|
||||
offsetBy n: Int,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
if n == 0 { return i }
|
||||
return n > 0
|
||||
? offsetForward(i, by: n, limitedBy: limit)
|
||||
: offsetBackward(i, by: -n, limitedBy: limit)
|
||||
if distance >= 0 {
|
||||
return limit >= i
|
||||
? offsetForward(i, by: distance, limitedBy: limit)
|
||||
: offsetForward(i, by: distance)
|
||||
} else {
|
||||
return limit <= i
|
||||
? offsetBackward(i, by: -distance, limitedBy: limit)
|
||||
: offsetBackward(i, by: -distance)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
|
||||
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
|
||||
else { fatalError("Index is out of bounds") }
|
||||
return index
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
|
||||
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
|
||||
else { fatalError("Index is out of bounds") }
|
||||
return index
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(
|
||||
_ i: Index, by n: Int, limitedBy limit: Index
|
||||
_ i: Index, by distance: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance >= 0)
|
||||
assert(limit >= i)
|
||||
|
||||
switch (i.position, limit.position) {
|
||||
case let (.first(i), .first(limit)):
|
||||
if limit >= i {
|
||||
// `limit` is relevant, so `base2` cannot be reached
|
||||
return base1.index(i, offsetBy: n, limitedBy: limit)
|
||||
.map(Index.init(first:))
|
||||
} else if let j = base1.index(i, offsetBy: n, limitedBy: base1.endIndex) {
|
||||
// the offset stays within the bounds of `base1`
|
||||
return convertIndex(j)
|
||||
} else {
|
||||
// the offset overflows the bounds of `base1` by `n - d`
|
||||
let d = base1.distance(from: i, to: base1.endIndex)
|
||||
return Index(second: base2.index(base2.startIndex, offsetBy: n - d))
|
||||
}
|
||||
return base1.index(i, offsetBy: distance, limitedBy: limit)
|
||||
.map(Index.init(first:))
|
||||
|
||||
case let (.first(i), .second(limit)):
|
||||
if let j = base1.index(i, offsetBy: n, limitedBy: base1.endIndex) {
|
||||
if let j = base1.index(i, offsetBy: distance, limitedBy: base1.endIndex) {
|
||||
// the offset stays within the bounds of `base1`
|
||||
return convertIndex(j)
|
||||
return normalizeIndex(j)
|
||||
} else {
|
||||
// the offset overflows the bounds of `base1` by `n - d`
|
||||
let d = base1.distance(from: i, to: base1.endIndex)
|
||||
return base2.index(base2.startIndex, offsetBy: n - d, limitedBy: limit)
|
||||
return base2.index(base2.startIndex, offsetBy: distance - d, limitedBy: limit)
|
||||
.map(Index.init(second:))
|
||||
}
|
||||
|
||||
case let (.second(i), .first):
|
||||
// `limit` has no effect here
|
||||
return Index(second: base2.index(i, offsetBy: n))
|
||||
case (.second, .first):
|
||||
// impossible because `limit >= i`
|
||||
fatalError()
|
||||
|
||||
case let (.second(i), .second(limit)):
|
||||
return base2.index(i, offsetBy: n, limitedBy: limit)
|
||||
return base2.index(i, offsetBy: distance, limitedBy: limit)
|
||||
.map(Index.init(second:))
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(
|
||||
_ i: Index, by n: Int, limitedBy limit: Index
|
||||
_ i: Index, by distance: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance >= 0)
|
||||
assert(limit <= i)
|
||||
|
||||
switch (i.position, limit.position) {
|
||||
case let (.first(i), .first(limit)):
|
||||
return base1.index(i, offsetBy: -n, limitedBy: limit)
|
||||
return base1.index(i, offsetBy: -distance, limitedBy: limit)
|
||||
.map(Index.init(first:))
|
||||
|
||||
case let (.first(i), .second):
|
||||
// `limit` has no effect here
|
||||
return Index(first: base1.index(i, offsetBy: -n))
|
||||
case (.first, .second):
|
||||
// impossible because `limit <= i`
|
||||
fatalError()
|
||||
|
||||
case let (.second(i), .first(limit)):
|
||||
if let j = base2.index(i, offsetBy: -n, limitedBy: base2.startIndex) {
|
||||
if let j = base2.index(i, offsetBy: -distance, limitedBy: base2.startIndex) {
|
||||
// the offset stays within the bounds of `base2`
|
||||
return Index(second: j)
|
||||
} else {
|
||||
// the offset overflows the bounds of `base2` by `n - d`
|
||||
let d = base2.distance(from: base2.startIndex, to: i)
|
||||
return base1.index(base1.endIndex, offsetBy: -(n - d), limitedBy: limit)
|
||||
return base1.index(base1.endIndex, offsetBy: -(distance - d), limitedBy: limit)
|
||||
.map(Index.init(first:))
|
||||
}
|
||||
|
||||
case let (.second(i), .second(limit)):
|
||||
if limit <= i {
|
||||
// `limit` is relevant, so `base1` cannot be reached
|
||||
return base2.index(i, offsetBy: -n, limitedBy: limit)
|
||||
.map(Index.init(second:))
|
||||
} else if let j = base2.index(i, offsetBy: -n, limitedBy: base2.startIndex) {
|
||||
// the offset stays within the bounds of `base2`
|
||||
return Index(second: j)
|
||||
} else {
|
||||
// the offset overflows the bounds of `base2` by `n - d`
|
||||
let d = base2.distance(from: base2.startIndex, to: i)
|
||||
return Index(first: base1.index(base1.endIndex, offsetBy: -(n - d)))
|
||||
}
|
||||
// `limit` is relevant, so `base1` cannot be reached
|
||||
return base2.index(i, offsetBy: -distance, limitedBy: limit)
|
||||
.map(Index.init(second:))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -254,7 +263,7 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
|
||||
}
|
||||
}
|
||||
|
||||
extension Chain2: BidirectionalCollection
|
||||
extension Chain2Sequence: BidirectionalCollection
|
||||
where Base1: BidirectionalCollection, Base2: BidirectionalCollection
|
||||
{
|
||||
@inlinable
|
||||
@@ -271,12 +280,9 @@ extension Chain2: BidirectionalCollection
|
||||
}
|
||||
}
|
||||
|
||||
extension Chain2: RandomAccessCollection
|
||||
extension Chain2Sequence: RandomAccessCollection
|
||||
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
|
||||
|
||||
extension Chain2: Equatable where Base1: Equatable, Base2: Equatable {}
|
||||
extension Chain2: Hashable where Base1: Hashable, Base2: Hashable {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// chain(_:_:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
@@ -308,20 +314,6 @@ extension Chain2: Hashable where Base1: Hashable, Base2: Hashable {}
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func chain<S1, S2>(_ s1: S1, _ s2: S2) -> Chain2<S1, S2> {
|
||||
Chain2(base1: s1, base2: s2)
|
||||
}
|
||||
|
||||
// MARK: - Deprecations
|
||||
|
||||
@available(*, deprecated, renamed: "Chain2")
|
||||
public typealias Chain = Chain2
|
||||
|
||||
extension Sequence {
|
||||
@available(*, deprecated, message: "Use the chain(_:_:) function, instead.")
|
||||
public func chained<S: Sequence>(with other: S) -> Chain2<Self, S>
|
||||
where Element == S.Element
|
||||
{
|
||||
Chain2(base1: self, base2: other)
|
||||
}
|
||||
public func chain<S1, S2>(_ s1: S1, _ s2: S2) -> Chain2Sequence<S1, S2> {
|
||||
Chain2Sequence(base1: s1, base2: s2)
|
||||
}
|
||||
+479
-136
@@ -10,10 +10,13 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A collection wrapper that breaks a collection into chunks based on a
|
||||
/// predicate or projection.
|
||||
public struct LazyChunked<Base: Collection, Subject> {
|
||||
/// predicate.
|
||||
///
|
||||
/// Call `lazy.chunked(by:)` on a collection to create an instance of this type.
|
||||
public struct ChunkedByCollection<Base: Collection, Subject> {
|
||||
/// The collection that this instance provides a view onto.
|
||||
public let base: Base
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
/// The projection function.
|
||||
@usableFromInline
|
||||
@@ -23,9 +26,9 @@ public struct LazyChunked<Base: Collection, Subject> {
|
||||
@usableFromInline
|
||||
internal let belongInSameGroup: (Subject, Subject) -> Bool
|
||||
|
||||
/// The upper bound of the first chunk.
|
||||
/// The end index of the first chunk.
|
||||
@usableFromInline
|
||||
internal var firstUpperBound: Base.Index
|
||||
internal var endOfFirstChunk: Base.Index
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
@@ -36,15 +39,15 @@ public struct LazyChunked<Base: Collection, Subject> {
|
||||
self.base = base
|
||||
self.projection = projection
|
||||
self.belongInSameGroup = belongInSameGroup
|
||||
self.firstUpperBound = base.startIndex
|
||||
self.endOfFirstChunk = base.startIndex
|
||||
|
||||
if !base.isEmpty {
|
||||
firstUpperBound = endOfChunk(startingAt: base.startIndex)
|
||||
endOfFirstChunk = endOfChunk(startingAt: base.startIndex)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension LazyChunked: LazyCollectionProtocol {
|
||||
extension ChunkedByCollection: Collection {
|
||||
/// A position in a chunked collection.
|
||||
public struct Index: Comparable {
|
||||
/// The range corresponding to the chunk at this position.
|
||||
@@ -74,14 +77,18 @@ extension LazyChunked: LazyCollectionProtocol {
|
||||
/// at the given index.
|
||||
@inlinable
|
||||
internal func endOfChunk(startingAt start: Base.Index) -> Base.Index {
|
||||
let subject = projection(base[start])
|
||||
return base[base.index(after: start)...]
|
||||
.endOfPrefix(while: { belongInSameGroup(subject, projection($0)) })
|
||||
var subject = projection(base[start])
|
||||
|
||||
return base[base.index(after: start)...].endOfPrefix(while: { element in
|
||||
let nextSubject = projection(element)
|
||||
defer { subject = nextSubject }
|
||||
return belongInSameGroup(subject, nextSubject)
|
||||
})
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
Index(base.startIndex..<firstUpperBound)
|
||||
Index(base.startIndex..<endOfFirstChunk)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@@ -105,9 +112,9 @@ extension LazyChunked: LazyCollectionProtocol {
|
||||
}
|
||||
}
|
||||
|
||||
extension LazyChunked.Index: Hashable where Base.Index: Hashable {}
|
||||
extension ChunkedByCollection.Index: Hashable where Base.Index: Hashable {}
|
||||
|
||||
extension LazyChunked: BidirectionalCollection
|
||||
extension ChunkedByCollection: BidirectionalCollection
|
||||
where Base: BidirectionalCollection
|
||||
{
|
||||
/// Returns the index in the base collection of the start of the chunk ending
|
||||
@@ -115,11 +122,13 @@ extension LazyChunked: BidirectionalCollection
|
||||
@inlinable
|
||||
internal func startOfChunk(endingAt end: Base.Index) -> Base.Index {
|
||||
let indexBeforeEnd = base.index(before: end)
|
||||
var subject = projection(base[indexBeforeEnd])
|
||||
|
||||
// Get the projected value of the last element in the range ending at `end`.
|
||||
let subject = projection(base[indexBeforeEnd])
|
||||
return base[..<indexBeforeEnd]
|
||||
.startOfSuffix(while: { belongInSameGroup(projection($0), subject) })
|
||||
return base[..<indexBeforeEnd].startOfSuffix(while: { element in
|
||||
let nextSubject = projection(element)
|
||||
defer { subject = nextSubject }
|
||||
return belongInSameGroup(nextSubject, subject)
|
||||
})
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@@ -130,97 +139,379 @@ extension LazyChunked: BidirectionalCollection
|
||||
}
|
||||
}
|
||||
|
||||
extension ChunkedByCollection: LazyCollectionProtocol {}
|
||||
|
||||
/// A collection wrapper that breaks a collection into chunks based on a
|
||||
/// predicate.
|
||||
///
|
||||
/// Call `lazy.chunked(on:)` on a collection to create an instance of this type.
|
||||
public struct ChunkedOnCollection<Base: Collection, Subject: Equatable> {
|
||||
@usableFromInline
|
||||
internal var chunked: ChunkedByCollection<Base, Subject>
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
base: Base,
|
||||
projection: @escaping (Base.Element) -> Subject
|
||||
) {
|
||||
self.chunked = ChunkedByCollection(
|
||||
base: base,
|
||||
projection: projection,
|
||||
belongInSameGroup: ==)
|
||||
}
|
||||
}
|
||||
|
||||
extension ChunkedOnCollection: Collection {
|
||||
public typealias Index = ChunkedByCollection<Base, Subject>.Index
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
chunked.startIndex
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
chunked.endIndex
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> (Subject, Base.SubSequence) {
|
||||
let subsequence = chunked[position]
|
||||
let subject = chunked.projection(subsequence.first!)
|
||||
return (subject, subsequence)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
chunked.index(after: i)
|
||||
}
|
||||
}
|
||||
|
||||
extension ChunkedOnCollection: BidirectionalCollection
|
||||
where Base: BidirectionalCollection
|
||||
{
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
chunked.index(before: i)
|
||||
}
|
||||
}
|
||||
|
||||
extension ChunkedOnCollection: LazyCollectionProtocol {}
|
||||
|
||||
/// A collection wrapper that evenly breaks a collection into a given number of
|
||||
/// chunks.
|
||||
public struct EvenlyChunkedCollection<Base: Collection> {
|
||||
/// The base collection.
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
/// The number of equal chunks the base collection is divided into.
|
||||
@usableFromInline
|
||||
internal let numberOfChunks: Int
|
||||
|
||||
/// The count of the base collection.
|
||||
@usableFromInline
|
||||
internal let baseCount: Int
|
||||
|
||||
/// The upper bound of the first chunk.
|
||||
@usableFromInline
|
||||
internal var firstUpperBound: Base.Index
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base, numberOfChunks: Int) {
|
||||
self.base = base
|
||||
self.numberOfChunks = numberOfChunks
|
||||
self.baseCount = base.count
|
||||
self.firstUpperBound = base.startIndex
|
||||
|
||||
if numberOfChunks > 0 {
|
||||
firstUpperBound = endOfChunk(startingAt: base.startIndex, offset: 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension EvenlyChunkedCollection {
|
||||
/// Returns the number of chunks with size `smallChunkSize + 1` at the start
|
||||
/// of this collection.
|
||||
@inlinable
|
||||
internal var numberOfLargeChunks: Int {
|
||||
baseCount % numberOfChunks
|
||||
}
|
||||
|
||||
/// Returns the size of a chunk at a given offset.
|
||||
@inlinable
|
||||
internal func sizeOfChunk(offset: Int) -> Int {
|
||||
let isLargeChunk = offset < numberOfLargeChunks
|
||||
return baseCount / numberOfChunks + (isLargeChunk ? 1 : 0)
|
||||
}
|
||||
|
||||
/// Returns the index in the base collection of the end of the chunk starting
|
||||
/// at the given index.
|
||||
@inlinable
|
||||
internal func endOfChunk(startingAt start: Base.Index, offset: Int) -> Base.Index {
|
||||
base.index(start, offsetBy: sizeOfChunk(offset: offset))
|
||||
}
|
||||
|
||||
/// Returns the index in the base collection of the start of the chunk ending
|
||||
/// at the given index.
|
||||
@inlinable
|
||||
internal func startOfChunk(endingAt end: Base.Index, offset: Int) -> Base.Index {
|
||||
base.index(end, offsetBy: -sizeOfChunk(offset: offset))
|
||||
}
|
||||
|
||||
/// Returns the index that corresponds to the chunk that starts at the given
|
||||
/// base index.
|
||||
@inlinable
|
||||
internal func indexOfChunk(startingAt start: Base.Index, offset: Int) -> Index {
|
||||
guard offset != numberOfChunks else { return endIndex }
|
||||
let end = endOfChunk(startingAt: start, offset: offset)
|
||||
return Index(start..<end, offset: offset)
|
||||
}
|
||||
|
||||
/// Returns the index that corresponds to the chunk that ends at the given
|
||||
/// base index.
|
||||
@inlinable
|
||||
internal func indexOfChunk(endingAt end: Base.Index, offset: Int) -> Index {
|
||||
let start = startOfChunk(endingAt: end, offset: offset)
|
||||
return Index(start..<end, offset: offset)
|
||||
}
|
||||
}
|
||||
|
||||
extension EvenlyChunkedCollection: Collection {
|
||||
public struct Index: Comparable {
|
||||
/// The range corresponding to the chunk at this position.
|
||||
@usableFromInline
|
||||
internal var baseRange: Range<Base.Index>
|
||||
|
||||
/// The offset corresponding to the chunk at this position. The first chunk
|
||||
/// has offset `0` and all other chunks have an offset `1` greater than the
|
||||
/// previous.
|
||||
@usableFromInline
|
||||
internal var offset: Int
|
||||
|
||||
@inlinable
|
||||
internal init(_ baseRange: Range<Base.Index>, offset: Int) {
|
||||
self.baseRange = baseRange
|
||||
self.offset = offset
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.offset == rhs.offset
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.offset < rhs.offset
|
||||
}
|
||||
}
|
||||
|
||||
public typealias Element = Base.SubSequence
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
Index(base.startIndex..<firstUpperBound, offset: 0)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
Index(base.endIndex..<base.endIndex, offset: numberOfChunks)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
precondition(i != endIndex, "Can't advance past endIndex")
|
||||
let start = i.baseRange.upperBound
|
||||
return indexOfChunk(startingAt: start, offset: i.offset + 1)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> Element {
|
||||
precondition(position != endIndex)
|
||||
return base[position.baseRange]
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||
/// Returns the base distance between two `EvenChunksCollection` indices
|
||||
/// from the end of one to the start of the other, when given their offsets.
|
||||
func baseDistance(from offsetA: Int, to offsetB: Int) -> Int {
|
||||
let smallChunkSize = baseCount / numberOfChunks
|
||||
let numberOfChunks = (offsetB - offsetA) - 1
|
||||
|
||||
let largeChunksEnd = Swift.min(self.numberOfLargeChunks, offsetB)
|
||||
let largeChunksStart = Swift.min(self.numberOfLargeChunks, offsetA + 1)
|
||||
let numberOfLargeChunks = largeChunksEnd - largeChunksStart
|
||||
|
||||
return smallChunkSize * numberOfChunks + numberOfLargeChunks
|
||||
}
|
||||
|
||||
if distance == 0 {
|
||||
return i
|
||||
} else if distance > 0 {
|
||||
let offset = i.offset + distance
|
||||
let baseOffset = baseDistance(from: i.offset, to: offset)
|
||||
let start = base.index(i.baseRange.upperBound, offsetBy: baseOffset)
|
||||
return indexOfChunk(startingAt: start, offset: offset)
|
||||
} else {
|
||||
let offset = i.offset + distance
|
||||
let baseOffset = baseDistance(from: offset, to: i.offset)
|
||||
let end = base.index(i.baseRange.lowerBound, offsetBy: -baseOffset)
|
||||
return indexOfChunk(endingAt: end, offset: offset)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? {
|
||||
if distance >= 0 {
|
||||
if (0..<distance).contains(self.distance(from: i, to: limit)) {
|
||||
return nil
|
||||
}
|
||||
} else {
|
||||
if (0..<(-distance)).contains(self.distance(from: limit, to: i)) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return index(i, offsetBy: distance)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
end.offset - start.offset
|
||||
}
|
||||
}
|
||||
|
||||
extension EvenlyChunkedCollection.Index: Hashable where Base.Index: Hashable {}
|
||||
|
||||
extension EvenlyChunkedCollection: BidirectionalCollection
|
||||
where Base: BidirectionalCollection
|
||||
{
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
precondition(i != startIndex, "Can't advance before startIndex")
|
||||
return indexOfChunk(endingAt: i.baseRange.lowerBound, offset: i.offset - 1)
|
||||
}
|
||||
}
|
||||
|
||||
extension EvenlyChunkedCollection: RandomAccessCollection
|
||||
where Base: RandomAccessCollection {}
|
||||
|
||||
extension EvenlyChunkedCollection: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
extension EvenlyChunkedCollection: LazyCollectionProtocol
|
||||
where Base: LazyCollectionProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// lazy.chunked(by:)
|
||||
// lazy.chunked(by:) / lazy.chunked(on:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension LazyCollectionProtocol {
|
||||
extension LazySequenceProtocol where Self: Collection, Elements: Collection {
|
||||
/// Returns a lazy collection of subsequences of this collection, chunked by
|
||||
/// the given predicate.
|
||||
///
|
||||
/// - Parameter belongInSameGroup: A closure that takes two adjacent elements
|
||||
/// of the sequence and returns whether or not they belong in the same group.
|
||||
///
|
||||
/// - Complexity: O(*n*), because the start index is pre-computed.
|
||||
@inlinable
|
||||
public func chunked(
|
||||
by belongInSameGroup: @escaping (Element, Element) -> Bool
|
||||
) -> LazyChunked<Elements, Element> {
|
||||
LazyChunked(
|
||||
) -> ChunkedByCollection<Elements, Element> {
|
||||
ChunkedByCollection(
|
||||
base: elements,
|
||||
projection: { $0 },
|
||||
belongInSameGroup: belongInSameGroup)
|
||||
}
|
||||
|
||||
/// Returns a lazy collection of subsequences of this collection, chunked by
|
||||
/// grouping elements that project to the same value.
|
||||
/// grouping elements that project to equal values.
|
||||
///
|
||||
/// - Parameter projection: A closure that takes an element in the sequence
|
||||
/// and returns an `Equatable` value that can be used to determine if adjacent
|
||||
/// elements belong in the same group.
|
||||
///
|
||||
/// - Complexity: O(*n*), because the start index is pre-computed.
|
||||
@inlinable
|
||||
public func chunked<Subject: Equatable>(
|
||||
public func chunked<Subject>(
|
||||
on projection: @escaping (Element) -> Subject
|
||||
) -> LazyChunked<Elements, Subject> {
|
||||
LazyChunked(
|
||||
) -> ChunkedOnCollection<Elements, Subject> {
|
||||
ChunkedOnCollection(
|
||||
base: elements,
|
||||
projection: projection,
|
||||
belongInSameGroup: ==)
|
||||
projection: projection)
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// chunked(by:)
|
||||
// chunked(by:) / chunked(on:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Collection {
|
||||
/// Returns a collection of subsequences of this collection, chunked by
|
||||
/// grouping elements that project to the same value according to the given
|
||||
/// predicate.
|
||||
/// Returns a collection of subsequences of this collection, chunked by the
|
||||
/// given predicate.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
@inlinable
|
||||
internal func chunked<Subject>(
|
||||
on projection: (Element) throws -> Subject,
|
||||
by belongInSameGroup: (Subject, Subject) throws -> Bool
|
||||
) rethrows -> [SubSequence] {
|
||||
guard !isEmpty else { return [] }
|
||||
var result: [SubSequence] = []
|
||||
|
||||
var start = startIndex
|
||||
var subject = try projection(self[start])
|
||||
|
||||
for (index, element) in indexed().dropFirst() {
|
||||
let nextSubject = try projection(element)
|
||||
if try !belongInSameGroup(subject, nextSubject) {
|
||||
result.append(self[start..<index])
|
||||
start = index
|
||||
subject = nextSubject
|
||||
}
|
||||
}
|
||||
|
||||
if start != endIndex {
|
||||
result.append(self[start..<endIndex])
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/// Returns a collection of subsequences of this collection, chunked by
|
||||
/// the given predicate.
|
||||
/// - Parameter belongInSameGroup: A closure that takes two adjacent elements
|
||||
/// of the collection and returns whether or not they belong in the same
|
||||
/// group.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
@inlinable
|
||||
public func chunked(
|
||||
by belongInSameGroup: (Element, Element) throws -> Bool
|
||||
) rethrows -> [SubSequence] {
|
||||
try chunked(on: { $0 }, by: belongInSameGroup)
|
||||
guard !isEmpty else { return [] }
|
||||
var result: [SubSequence] = []
|
||||
|
||||
var start = startIndex
|
||||
var current = self[start]
|
||||
|
||||
for (index, element) in indexed().dropFirst() {
|
||||
if try !belongInSameGroup(current, element) {
|
||||
result.append(self[start..<index])
|
||||
start = index
|
||||
}
|
||||
current = element
|
||||
}
|
||||
|
||||
if start != endIndex {
|
||||
result.append(self[start...])
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/// Returns a collection of subsequences of this collection, chunked by
|
||||
/// grouping elements that project to the same value.
|
||||
/// grouping elements that project to equal values.
|
||||
///
|
||||
/// - Parameter projection: A closure that takes an element in the collection
|
||||
/// and returns an `Equatable` value that can be used to determine if adjacent
|
||||
/// elements belong in the same group.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
@inlinable
|
||||
public func chunked<Subject: Equatable>(
|
||||
on projection: (Element) throws -> Subject
|
||||
) rethrows -> [SubSequence] {
|
||||
try chunked(on: projection, by: ==)
|
||||
) rethrows -> [(Subject, SubSequence)] {
|
||||
guard !isEmpty else { return [] }
|
||||
var result: [(Subject, SubSequence)] = []
|
||||
|
||||
var start = startIndex
|
||||
var subject = try projection(self[start])
|
||||
|
||||
for (index, element) in indexed().dropFirst() {
|
||||
let nextSubject = try projection(element)
|
||||
if subject != nextSubject {
|
||||
result.append((subject, self[start..<index]))
|
||||
start = index
|
||||
subject = nextSubject
|
||||
}
|
||||
}
|
||||
|
||||
if start != endIndex {
|
||||
result.append((subject, self[start...]))
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,17 +519,18 @@ extension Collection {
|
||||
// chunks(ofCount:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A collection that presents the elements of its base collection
|
||||
/// in `SubSequence` chunks of any given count.
|
||||
/// A collection that presents the elements of its base collection in
|
||||
/// `SubSequence` chunks of any given count.
|
||||
///
|
||||
/// A `ChunkedByCount` is a lazy view on the base Collection, but it does not implicitly confer
|
||||
/// laziness on algorithms applied to its result. In other words, for ordinary collections `c`:
|
||||
/// A `ChunksOfCountCollection` is a lazy view on the base `Collection`, but it
|
||||
/// does not implicitly confer laziness on algorithms applied to its result. In
|
||||
/// other words, for ordinary collections `c`:
|
||||
///
|
||||
/// * `c.chunks(ofCount: 3)` does not create new storage
|
||||
/// * `c.chunks(ofCount: 3).map(f)` maps eagerly and returns a new array
|
||||
/// * `c.lazy.chunks(ofCount: 3).map(f)` maps lazily and returns a `LazyMapCollection`
|
||||
public struct ChunkedByCount<Base: Collection> {
|
||||
|
||||
/// * `c.lazy.chunks(ofCount: 3).map(f)` maps lazily and returns a
|
||||
/// `LazyMapCollection`
|
||||
public struct ChunksOfCountCollection<Base: Collection> {
|
||||
public typealias Element = Base.SubSequence
|
||||
|
||||
@usableFromInline
|
||||
@@ -248,10 +540,10 @@ public struct ChunkedByCount<Base: Collection> {
|
||||
internal let chunkCount: Int
|
||||
|
||||
@usableFromInline
|
||||
internal var startUpperBound: Base.Index
|
||||
internal var endOfFirstChunk: Base.Index
|
||||
|
||||
/// Creates a view instance that presents the elements of `base`
|
||||
/// in `SubSequence` chunks of the given count.
|
||||
/// Creates a view instance that presents the elements of `base` in
|
||||
/// `SubSequence` chunks of the given count.
|
||||
///
|
||||
/// - Complexity: O(*n*), because the start index is pre-computed.
|
||||
@inlinable
|
||||
@@ -259,16 +551,16 @@ public struct ChunkedByCount<Base: Collection> {
|
||||
self.base = _base
|
||||
self.chunkCount = _chunkCount
|
||||
|
||||
// Compute the start index upfront in order to make
|
||||
// start index a O(1) lookup.
|
||||
self.startUpperBound = _base.index(
|
||||
// Compute the start index upfront in order to make start index a O(1)
|
||||
// lookup.
|
||||
self.endOfFirstChunk = _base.index(
|
||||
_base.startIndex, offsetBy: _chunkCount,
|
||||
limitedBy: _base.endIndex
|
||||
) ?? _base.endIndex
|
||||
}
|
||||
}
|
||||
|
||||
extension ChunkedByCount: Collection {
|
||||
extension ChunksOfCountCollection: Collection {
|
||||
public struct Index {
|
||||
@usableFromInline
|
||||
internal let baseRange: Range<Base.Index>
|
||||
@@ -282,8 +574,9 @@ extension ChunkedByCount: Collection {
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
Index(_baseRange: base.startIndex..<startUpperBound)
|
||||
Index(_baseRange: base.startIndex..<endOfFirstChunk)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
Index(_baseRange: base.endIndex..<base.endIndex)
|
||||
@@ -292,13 +585,13 @@ extension ChunkedByCount: Collection {
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public subscript(i: Index) -> Element {
|
||||
precondition(i < endIndex, "Index out of range")
|
||||
precondition(i != endIndex, "Index out of range")
|
||||
return base[i.baseRange]
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
precondition(i < endIndex, "Advancing past end index")
|
||||
precondition(i != endIndex, "Advancing past end index")
|
||||
let baseIdx = base.index(
|
||||
i.baseRange.upperBound, offsetBy: chunkCount,
|
||||
limitedBy: base.endIndex
|
||||
@@ -307,30 +600,30 @@ extension ChunkedByCount: Collection {
|
||||
}
|
||||
}
|
||||
|
||||
extension ChunkedByCount.Index: Comparable {
|
||||
extension ChunksOfCountCollection.Index: Comparable {
|
||||
@inlinable
|
||||
public static func == (lhs: ChunkedByCount.Index,
|
||||
rhs: ChunkedByCount.Index) -> Bool {
|
||||
public static func == (lhs: ChunksOfCountCollection.Index,
|
||||
rhs: ChunksOfCountCollection.Index) -> Bool {
|
||||
lhs.baseRange.lowerBound == rhs.baseRange.lowerBound
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: ChunkedByCount.Index,
|
||||
rhs: ChunkedByCount.Index) -> Bool {
|
||||
public static func < (lhs: ChunksOfCountCollection.Index,
|
||||
rhs: ChunksOfCountCollection.Index) -> Bool {
|
||||
lhs.baseRange.lowerBound < rhs.baseRange.lowerBound
|
||||
}
|
||||
}
|
||||
|
||||
extension ChunkedByCount:
|
||||
extension ChunksOfCountCollection:
|
||||
BidirectionalCollection, RandomAccessCollection
|
||||
where Base: RandomAccessCollection {
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
precondition(i > startIndex, "Advancing past start index")
|
||||
precondition(i != startIndex, "Advancing past start index")
|
||||
|
||||
var offset = chunkCount
|
||||
if i.baseRange.lowerBound == base.endIndex {
|
||||
let remainder = base.count%chunkCount
|
||||
let remainder = base.count % chunkCount
|
||||
if remainder != 0 {
|
||||
offset = remainder
|
||||
}
|
||||
@@ -344,7 +637,7 @@ where Base: RandomAccessCollection {
|
||||
}
|
||||
}
|
||||
|
||||
extension ChunkedByCount {
|
||||
extension ChunksOfCountCollection {
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
let distance =
|
||||
@@ -412,12 +705,12 @@ extension ChunkedByCount {
|
||||
_ i: Index, _ distance: Int
|
||||
) -> Int {
|
||||
if i == endIndex {
|
||||
let remainder = base.count%chunkCount
|
||||
let remainder = base.count % chunkCount
|
||||
// We have to take it into account when calculating offsets.
|
||||
if remainder != 0 {
|
||||
// Distance "minus" one(at this point distance is negative)
|
||||
// because we need to adjust for the last position that have
|
||||
// a variadic(remainder) number of elements.
|
||||
// Distance "minus" one (at this point distance is negative) because we
|
||||
// need to adjust for the last position that have a variadic (remainder)
|
||||
// number of elements.
|
||||
return ((distance + 1) * chunkCount) - remainder
|
||||
}
|
||||
}
|
||||
@@ -438,7 +731,7 @@ extension ChunkedByCount {
|
||||
)
|
||||
}
|
||||
|
||||
// Helper to compute index(offsetBy:) index.
|
||||
// Helper to compute `index(offsetBy:)` index.
|
||||
@inlinable
|
||||
internal func makeOffsetIndex(
|
||||
from i: Index, baseBound: Base.Index, distance: Int, baseDistance: Int,
|
||||
@@ -451,13 +744,12 @@ extension ChunkedByCount {
|
||||
|
||||
if let limit = limit {
|
||||
if baseIdx == nil {
|
||||
// If we past the bounds while advancing forward and the
|
||||
// limit is the `endIndex`, since the computation on base
|
||||
// don't take into account the remainder, we have to make
|
||||
// sure that passing the bound was because of the distance
|
||||
// not just because of a remainder. Special casing is less
|
||||
// expensive than always use count(which could be O(n) for
|
||||
// non-random access collection base) to compute the base
|
||||
// If we passed the bounds while advancing forward, and the limit is the
|
||||
// `endIndex`, since the computation on `base` don't take into account
|
||||
// the remainder, we have to make sure that passing the bound was
|
||||
// because of the distance not just because of a remainder. Special
|
||||
// casing is less expensive than always using `count` (which could be
|
||||
// O(n) for non-random access collection base) to compute the base
|
||||
// distance taking remainder into account.
|
||||
if baseDistance > 0 && limit == endIndex {
|
||||
if self.distance(from: i, to: limit) < distance {
|
||||
@@ -485,47 +777,98 @@ extension ChunkedByCount {
|
||||
}
|
||||
|
||||
extension Collection {
|
||||
/// Returns a `ChunkedCollection<Self>` view presenting the elements
|
||||
/// in chunks with count of the given count parameter.
|
||||
/// Returns a collection of subsequences, each with up to the specified
|
||||
/// length.
|
||||
///
|
||||
/// - Parameter size: The size of the chunks. If the count parameter
|
||||
/// is evenly divided by the count of the base `Collection` all the
|
||||
/// chunks will have the count equals to size.
|
||||
/// Otherwise, the last chunk will contain the remaining elements.
|
||||
/// If the number of elements in the collection is evenly divided by `count`,
|
||||
/// then every chunk will have a length equal to `count`. Otherwise, every
|
||||
/// chunk but the last will have a length equal to `count`, with the
|
||||
/// remaining elements in the last chunk.
|
||||
///
|
||||
/// let c = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||
/// print(c.chunks(ofCount: 5).map(Array.init))
|
||||
/// // [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
|
||||
/// let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||
/// for chunk in numbers.chunks(ofCount: 5) {
|
||||
/// print(chunk)
|
||||
/// }
|
||||
/// // [1, 2, 3, 4, 5]
|
||||
/// // [6, 7, 8, 9, 10]
|
||||
///
|
||||
/// print(c.chunks(ofCount: 3).map(Array.init))
|
||||
/// // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
|
||||
/// for chunk in numbers.chunks(ofCount: 3) {
|
||||
/// print(chunk)
|
||||
/// }
|
||||
/// // [1, 2, 3]
|
||||
/// // [4, 5, 5]
|
||||
/// // [7, 8, 9]
|
||||
/// // [10]
|
||||
///
|
||||
/// - Parameter count: The desired size of each chunk.
|
||||
/// - Returns: A collection of consescutive, non-overlapping subseqeunces of
|
||||
/// this collection, where each subsequence (except possibly the last) has
|
||||
/// the length `count`.
|
||||
///
|
||||
/// - Complexity: O(1) if the collection conforms to `RandomAccessCollection`;
|
||||
/// otherwise, O(*k*), where *k* is equal to `count`.
|
||||
///
|
||||
/// - Complexity: O(*n*), because the start index is pre-computed.
|
||||
@inlinable
|
||||
public func chunks(ofCount count: Int) -> ChunkedByCount<Self> {
|
||||
public func chunks(ofCount count: Int) -> ChunksOfCountCollection<Self> {
|
||||
precondition(count > 0, "Cannot chunk with count <= 0!")
|
||||
return ChunkedByCount(_base: self, _chunkCount: count)
|
||||
return ChunksOfCountCollection(_base: self, _chunkCount: count)
|
||||
}
|
||||
}
|
||||
|
||||
// Conditional conformances.
|
||||
extension ChunkedByCount: Equatable where Base: Equatable {}
|
||||
extension ChunksOfCountCollection.Index: Hashable where Base.Index: Hashable {}
|
||||
|
||||
// Since we have another stored property of type `Index` on the
|
||||
// collection, synthesis of `Hashble` conformace would require
|
||||
// a `Base.Index: Hashable` constraint, so we implement the hasher
|
||||
// only in terms of `base`. Since the computed index is based on it,
|
||||
// it should not make a difference here.
|
||||
extension ChunkedByCount: Hashable where Base: Hashable {
|
||||
@inlinable
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(base)
|
||||
}
|
||||
}
|
||||
extension ChunkedByCount.Index: Hashable where Base.Index: Hashable {}
|
||||
|
||||
// Lazy conditional conformance.
|
||||
extension ChunkedByCount: LazySequenceProtocol
|
||||
extension ChunksOfCountCollection: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
extension ChunkedByCount: LazyCollectionProtocol
|
||||
|
||||
extension ChunksOfCountCollection: LazyCollectionProtocol
|
||||
where Base: LazyCollectionProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// evenlyChunked(in:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Collection {
|
||||
/// Returns a collection of evenly divided consecutive subsequences of this
|
||||
/// collection.
|
||||
///
|
||||
/// This method divides the collection into a given number of evenly sized
|
||||
/// chunks. If the length of the collection is not divisible by `count`, the
|
||||
/// chunks at the start will be longer than the chunks at the end, like in
|
||||
/// this example:
|
||||
///
|
||||
/// for chunk in "Hello, world!".evenlyChunked(in: 5) {
|
||||
/// print(chunk)
|
||||
/// }
|
||||
/// // "Hel"
|
||||
/// // "lo,"
|
||||
/// // " wo"
|
||||
/// // "rl"
|
||||
/// // "d!"
|
||||
///
|
||||
/// If the number passed as `count` is greater than the number of elements in
|
||||
/// the collection, the result will include one or more empty subsequences.
|
||||
///
|
||||
/// for chunk in "Hi!".evenlyChunked(in: 5) {
|
||||
/// print(chunk)
|
||||
/// }
|
||||
/// // "H"
|
||||
/// // "i"
|
||||
/// // "!"
|
||||
/// // ""
|
||||
/// // ""
|
||||
///
|
||||
/// - Parameter count: The number of chunks to evenly divide this collection
|
||||
/// into. If this collection is non-empty, `count` must be greater than
|
||||
/// zero; otherwise, `count` may be zero or greater.
|
||||
/// - Returns: A collection of `count` subsequences of this collection,
|
||||
/// divided as evenly as possible.
|
||||
///
|
||||
/// - Complexity: O(1) if the collection conforms to `RandomAccessCollection`;
|
||||
/// otherwise, O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
public func evenlyChunked(in count: Int) -> EvenlyChunkedCollection<Self> {
|
||||
precondition(count >= 0, "Can't divide into a negative number of chunks")
|
||||
precondition(count > 0 || isEmpty, "Can't divide a non-empty collection into 0 chunks")
|
||||
return EvenlyChunkedCollection(base: self, numberOfChunks: count)
|
||||
}
|
||||
}
|
||||
@@ -10,20 +10,24 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A collection wrapper that generates combinations of a base collection.
|
||||
public struct Combinations<Base: Collection> {
|
||||
public struct CombinationsSequence<Base: Collection> {
|
||||
/// The collection to iterate over for combinations.
|
||||
public let base: Base
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let baseCount: Int
|
||||
|
||||
/// The range of accepted sizes of combinations.
|
||||
///
|
||||
/// - Note: This may be `nil` if the attempted range entirely exceeds the
|
||||
/// upper bounds of the size of the `base` collection.
|
||||
@usableFromInline
|
||||
internal let kRange: Range<Int>?
|
||||
|
||||
/// Initializes a `Combinations` for all combinations of `base` of size `k`.
|
||||
/// Initializes a `CombinationsSequence` for all combinations of `base` of
|
||||
/// size `k`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - base: The collection to iterate over for combinations.
|
||||
/// - k: The expected size of each combination.
|
||||
@@ -32,8 +36,9 @@ public struct Combinations<Base: Collection> {
|
||||
self.init(base, kRange: k...k)
|
||||
}
|
||||
|
||||
/// Initializes a `Combinations` for all combinations of `base` of sizes
|
||||
/// within a given range.
|
||||
/// Initializes a `CombinationsSequence` for all combinations of `base` of
|
||||
/// sizes within a given range.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - base: The collection to iterate over for combinations.
|
||||
/// - kRange: The range of accepted sizes of combinations.
|
||||
@@ -75,13 +80,14 @@ public struct Combinations<Base: Collection> {
|
||||
}
|
||||
}
|
||||
|
||||
extension Combinations: Sequence {
|
||||
/// The iterator for a `Combinations` instance.
|
||||
extension CombinationsSequence: Sequence {
|
||||
/// The iterator for a `CombinationsSequence` instance.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
/// The current range of accepted sizes of combinations.
|
||||
///
|
||||
/// - Note: The range is contracted until empty while iterating over
|
||||
/// combinations of different sizes. When the range is empty, iteration is
|
||||
/// finished.
|
||||
@@ -98,7 +104,7 @@ extension Combinations: Sequence {
|
||||
internal var indexes: [Base.Index]
|
||||
|
||||
@inlinable
|
||||
internal init(_ combinations: Combinations) {
|
||||
internal init(_ combinations: CombinationsSequence) {
|
||||
self.base = combinations.base
|
||||
self.kRange = combinations.kRange ?? 0..<0
|
||||
self.indexes = Array(combinations.base.indices.prefix(kRange.lowerBound))
|
||||
@@ -174,14 +180,14 @@ extension Combinations: Sequence {
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension Combinations: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
extension Combinations: Equatable where Base: Equatable {}
|
||||
extension Combinations: Hashable where Base: Hashable {}
|
||||
extension CombinationsSequence: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// combinations(ofCount:)
|
||||
@@ -244,16 +250,16 @@ extension Collection {
|
||||
/// limited range is empty, the resulting sequence has no elements.
|
||||
///
|
||||
/// - Parameter kRange: The range of numbers of elements to include in each
|
||||
/// combination.
|
||||
/// combination.
|
||||
///
|
||||
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
|
||||
/// is the number of elements in the base collection, since `Combinations`
|
||||
/// accesses the `count` of the base collection.
|
||||
/// is the number of elements in the base collection, since
|
||||
/// `CombinationsSequence` accesses the `count` of the base collection.
|
||||
@inlinable
|
||||
public func combinations<R: RangeExpression>(
|
||||
ofCount kRange: R
|
||||
) -> Combinations<Self> where R.Bound == Int {
|
||||
return Combinations(self, kRange: kRange)
|
||||
) -> CombinationsSequence<Self> where R.Bound == Int {
|
||||
CombinationsSequence(self, kRange: kRange)
|
||||
}
|
||||
|
||||
/// Returns a collection of combinations of this collection's elements, with
|
||||
@@ -283,11 +289,11 @@ extension Collection {
|
||||
/// - Parameter k: The number of elements to include in each combination.
|
||||
///
|
||||
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
|
||||
/// is the number of elements in the base collection, since `Combinations`
|
||||
/// accesses the `count` of the base collection.
|
||||
/// is the number of elements in the base collection, since
|
||||
/// `CombinationsSequence` accesses the `count` of the base collection.
|
||||
@inlinable
|
||||
public func combinations(ofCount k: Int) -> Combinations<Self> {
|
||||
public func combinations(ofCount k: Int) -> CombinationsSequence<Self> {
|
||||
precondition(k >= 0, "Can't have combinations with a negative number of elements.")
|
||||
return Combinations(self, k: k)
|
||||
return CombinationsSequence(self, k: k)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A `Sequence` that iterates over every non-nil element from the original
|
||||
/// `Sequence`.
|
||||
public struct CompactedSequence<Base: Sequence, Element>: Sequence
|
||||
where Base.Element == Element? {
|
||||
|
||||
@usableFromInline
|
||||
let base: Base
|
||||
|
||||
@inlinable
|
||||
init(base: Base) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
var base: Base.Iterator
|
||||
|
||||
@inlinable
|
||||
init(base: Base.Iterator) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Element? {
|
||||
while let wrapped = base.next() {
|
||||
guard let some = wrapped else { continue }
|
||||
return some
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(base: base.makeIterator())
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
/// Returns a new `Sequence` that iterates over every non-nil element from the
|
||||
/// original `Sequence`.
|
||||
///
|
||||
/// Produces the same result as `c.compactMap { $0 }`.
|
||||
///
|
||||
/// let c = [1, nil, 2, 3, nil]
|
||||
/// for num in c.compacted() {
|
||||
/// print(num)
|
||||
/// }
|
||||
/// // 1
|
||||
/// // 2
|
||||
/// // 3
|
||||
///
|
||||
/// - Returns: A `Sequence` where the element is the unwrapped original
|
||||
/// element and iterates over every non-nil element from the original
|
||||
/// `Sequence`.
|
||||
///
|
||||
/// Complexity: O(1)
|
||||
@inlinable
|
||||
public func compacted<Unwrapped>() -> CompactedSequence<Self, Unwrapped>
|
||||
where Element == Unwrapped? {
|
||||
CompactedSequence(base: self)
|
||||
}
|
||||
}
|
||||
|
||||
/// A `Collection` that iterates over every non-nil element from the original
|
||||
/// `Collection`.
|
||||
public struct CompactedCollection<Base: Collection, Element>: Collection
|
||||
where Base.Element == Element? {
|
||||
|
||||
@usableFromInline
|
||||
let base: Base
|
||||
|
||||
@inlinable
|
||||
init(base: Base) {
|
||||
self.base = base
|
||||
let idx = base.firstIndex(where: { $0 != nil }) ?? base.endIndex
|
||||
self.startIndex = Index(base: idx)
|
||||
}
|
||||
|
||||
public struct Index {
|
||||
@usableFromInline
|
||||
let base: Base.Index
|
||||
|
||||
@inlinable
|
||||
init(base: Base.Index) {
|
||||
self.base = base
|
||||
}
|
||||
}
|
||||
|
||||
public var startIndex: Index
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index { Index(base: base.endIndex) }
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> Element {
|
||||
base[position.base]!
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
precondition(i != endIndex, "Index out of bounds")
|
||||
|
||||
let baseIdx = base.index(after: i.base)
|
||||
guard let idx = base[baseIdx...].firstIndex(where: { $0 != nil })
|
||||
else { return endIndex }
|
||||
return Index(base: idx)
|
||||
}
|
||||
}
|
||||
|
||||
extension CompactedCollection: BidirectionalCollection
|
||||
where Base: BidirectionalCollection {
|
||||
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
precondition(i != startIndex, "Index out of bounds")
|
||||
|
||||
guard let idx =
|
||||
base[startIndex.base..<i.base]
|
||||
.lastIndex(where: { $0 != nil })
|
||||
else { fatalError("Index out of bounds") }
|
||||
return Index(base: idx)
|
||||
}
|
||||
}
|
||||
|
||||
extension CompactedCollection.Index: Comparable {
|
||||
@inlinable
|
||||
public static func < (lhs: CompactedCollection.Index,
|
||||
rhs: CompactedCollection.Index) -> Bool {
|
||||
lhs.base < rhs.base
|
||||
}
|
||||
}
|
||||
|
||||
extension CompactedCollection.Index: Hashable
|
||||
where Base.Index: Hashable {}
|
||||
|
||||
extension Collection {
|
||||
/// Returns a new `Collection` that iterates over every non-nil element from
|
||||
/// the original `Collection`.
|
||||
///
|
||||
/// Produces the same result as `c.compactMap { $0 }`.
|
||||
///
|
||||
/// let c = [1, nil, 2, 3, nil]
|
||||
/// for num in c.compacted() {
|
||||
/// print(num)
|
||||
/// }
|
||||
/// // 1
|
||||
/// // 2
|
||||
/// // 3
|
||||
///
|
||||
/// - Returns: A `Collection` where the element is the unwrapped original
|
||||
/// element and iterates over every non-nil element from the original
|
||||
/// `Collection`.
|
||||
///
|
||||
/// Complexity: O(*n*) where *n* is the number of elements in the
|
||||
/// original `Collection`.
|
||||
@inlinable
|
||||
public func compacted<Unwrapped>() -> CompactedCollection<Self, Unwrapped>
|
||||
where Element == Unwrapped?
|
||||
{
|
||||
CompactedCollection(base: self)
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Protocol Conformances
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension CompactedSequence: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
extension CompactedCollection: LazySequenceProtocol, LazyCollectionProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
+118
-11
@@ -10,9 +10,10 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A collection wrapper that repeats the elements of a base collection.
|
||||
public struct Cycle<Base: Collection> {
|
||||
public struct CycledSequence<Base: Collection> {
|
||||
/// The collection to repeat.
|
||||
public let base: Base
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base) {
|
||||
@@ -20,14 +21,14 @@ public struct Cycle<Base: Collection> {
|
||||
}
|
||||
}
|
||||
|
||||
extension Cycle: Sequence {
|
||||
/// The iterator for a `Cycle` sequence.
|
||||
extension CycledSequence: Sequence {
|
||||
/// The iterator for a `CycledSequence` instance.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
let base: Base
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
var current: Base.Index
|
||||
internal var current: Base.Index
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base) {
|
||||
@@ -54,7 +55,113 @@ extension Cycle: Sequence {
|
||||
}
|
||||
}
|
||||
|
||||
extension Cycle: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
extension CycledSequence: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
/// A collection wrapper that repeats the elements of a base collection for a
|
||||
/// finite number of times.
|
||||
public struct CycledTimesCollection<Base: Collection> {
|
||||
/// A `Product2Sequence` instance for iterating the base collection.
|
||||
@usableFromInline
|
||||
internal let product: Product2Sequence<Range<Int>, Base>
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base, times: Int) {
|
||||
self.product = Product2Sequence(0..<times, base)
|
||||
}
|
||||
}
|
||||
|
||||
extension CycledTimesCollection: Collection {
|
||||
public typealias Element = Base.Element
|
||||
|
||||
public struct Index: Comparable {
|
||||
/// The index corresponding to the `Product2Sequence` index at this
|
||||
/// position.
|
||||
@usableFromInline
|
||||
internal let productIndex: Product2Sequence<Range<Int>, Base>.Index
|
||||
|
||||
@inlinable
|
||||
internal init(_ productIndex: Product2Sequence<Range<Int>, Base>.Index) {
|
||||
self.productIndex = productIndex
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func == (lhs: Index, rhs: Index) -> Bool {
|
||||
lhs.productIndex == rhs.productIndex
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
lhs.productIndex < rhs.productIndex
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
Index(product.startIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
Index(product.endIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(_ index: Index) -> Element {
|
||||
product[index.productIndex].1
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
let productIndex = product.index(after: i.productIndex)
|
||||
return Index(productIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
product.distance(from: start.productIndex, to: end.productIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||
let productIndex = product.index(i.productIndex, offsetBy: distance)
|
||||
return Index(productIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(
|
||||
_ i: Index,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
guard let productIndex = product.index(
|
||||
i.productIndex,
|
||||
offsetBy: distance,
|
||||
limitedBy: limit.productIndex)
|
||||
else { return nil }
|
||||
return Index(productIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var count: Int {
|
||||
product.count
|
||||
}
|
||||
}
|
||||
|
||||
extension CycledTimesCollection: BidirectionalCollection
|
||||
where Base: BidirectionalCollection {
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
let productIndex = product.index(before: i.productIndex)
|
||||
return Index(productIndex)
|
||||
}
|
||||
}
|
||||
|
||||
extension CycledTimesCollection: RandomAccessCollection
|
||||
where Base: RandomAccessCollection {}
|
||||
|
||||
extension CycledTimesCollection: LazySequenceProtocol, LazyCollectionProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// cycled()
|
||||
@@ -87,8 +194,8 @@ extension Collection {
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func cycled() -> Cycle<Self> {
|
||||
Cycle(base: self)
|
||||
public func cycled() -> CycledSequence<Self> {
|
||||
CycledSequence(base: self)
|
||||
}
|
||||
|
||||
/// Returns a sequence that repeats the elements of this collection the
|
||||
@@ -109,7 +216,7 @@ extension Collection {
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func cycled(times: Int) -> FlattenSequence<Repeated<Self>> {
|
||||
repeatElement(self, count: times).joined()
|
||||
public func cycled(times: Int) -> CycledTimesCollection<Self> {
|
||||
CycledTimesCollection(base: self, times: times)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
# ``Algorithms``
|
||||
|
||||
**Swift Algorithms** is an open-source package of sequence and collection algorithms,
|
||||
along with their related types.
|
||||
|
||||
## Overview
|
||||
|
||||
The Algorithms package provides a variety of sequence and collection operations, letting you cycle over a collection's elements, find combinations and permutations, create a random sample, and more.
|
||||
|
||||
For example, the package includes a group of "chunking" methods, each of which breaks a collection into consecutive subsequences. One version tests adjacent elements to find the breaking point between chunks — you can use it to quickly separate an array into ascending runs:
|
||||
|
||||
```swift
|
||||
let numbers = [10, 20, 30, 10, 40, 40, 10, 20]
|
||||
let chunks = numbers.chunked(by: { $0 <= $1 })
|
||||
// [[10, 20, 30], [10, 40, 40], [10, 20]]
|
||||
```
|
||||
|
||||
Another version looks for a change in the transformation of each successive value. You can use that to separate a list of names into groups by the first character:
|
||||
|
||||
```swift
|
||||
let names = ["Cassie", "Chloe", "Jasmine", "Jordan", "Taylor"]
|
||||
let chunks = names.chunked(on: \.first)
|
||||
// [["Cassie", "Chloe"], ["Jasmine", "Jordan"], ["Taylor"]]
|
||||
```
|
||||
|
||||
Explore more chunking methods and the remainder of the Algorithms package, grouped in the following topics.
|
||||
|
||||
## Topics
|
||||
|
||||
- <doc:CombinationsPermutations>
|
||||
- <doc:SlicingSplitting>
|
||||
- <doc:Chunking>
|
||||
- <doc:Joining>
|
||||
- <doc:Extending>
|
||||
- <doc:Trimming>
|
||||
- <doc:Sampling>
|
||||
- <doc:MinAndMax>
|
||||
- <doc:Selecting>
|
||||
- <doc:Filtering>
|
||||
- <doc:Reductions>
|
||||
- <doc:Partitioning>
|
||||
@@ -0,0 +1,40 @@
|
||||
# Chunking
|
||||
|
||||
Break collections into consecutive chunks by length, count, or based on closure-based logic.
|
||||
|
||||
## Overview
|
||||
|
||||
_Chunking_ is the process of breaking a collection into consecutive subsequences, without dropping or duplicating any of the collection's elements. After chunking a collection, joining the resulting subsequences produces the original collection of elements, unlike _splitting_, which consumes the separator element(s).
|
||||
|
||||
```swift
|
||||
let names = ["Ji-sun", "Jin-su", "Min-jae", "Young-ho"]
|
||||
let evenlyChunked = names.chunks(ofCount: 2)
|
||||
// ~ [["Ji-sun", "Jin-su"], ["Min-jae", "Young-ho"]]
|
||||
|
||||
let chunkedByFirstLetter = names.chunked(on: \.first)
|
||||
// equivalent to [("J", ["Ji-sun", "Jin-su"]), ("M", ["Min-jae"]), ("Y", ["Young-ho"])]
|
||||
```
|
||||
|
||||
## Topics
|
||||
|
||||
### Chunking a Collection by Count
|
||||
|
||||
- ``Swift/Collection/chunks(ofCount:)``
|
||||
- ``Swift/Collection/evenlyChunked(in:)``
|
||||
|
||||
### Chunking a Collection by Predicate
|
||||
|
||||
- ``Swift/Collection/chunked(by:)``
|
||||
- ``Swift/LazySequenceProtocol/chunked(by:)``
|
||||
|
||||
### Chunking a Collection by Subject
|
||||
|
||||
- ``Swift/Collection/chunked(on:)``
|
||||
- ``Swift/LazySequenceProtocol/chunked(on:)``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``ChunkedByCollection``
|
||||
- ``ChunkedOnCollection``
|
||||
- ``ChunksOfCountCollection``
|
||||
- ``EvenlyChunkedCollection``
|
||||
@@ -0,0 +1,32 @@
|
||||
# Combinations and Permutations
|
||||
|
||||
Find the combinations and permutations of any collection's elements,
|
||||
or the product of two different collections.
|
||||
|
||||
## Topics
|
||||
|
||||
### Combinations
|
||||
|
||||
- ``Swift/Collection/combinations(ofCount:)-26o4x``
|
||||
- ``Swift/Collection/combinations(ofCount:)-53jql``
|
||||
|
||||
### Permutations
|
||||
|
||||
- ``Swift/Collection/permutations(ofCount:)-7rc99``
|
||||
- ``Swift/Collection/permutations(ofCount:)-5zvhn``
|
||||
|
||||
### Unique Permutations
|
||||
|
||||
- ``Swift/Collection/uniquePermutations(ofCount:)-2extq``
|
||||
- ``Swift/Collection/uniquePermutations(ofCount:)-48r1k``
|
||||
|
||||
### Product
|
||||
|
||||
- ``product(_:_:)``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``CombinationsSequence``
|
||||
- ``PermutationsSequence``
|
||||
- ``UniquePermutationsSequence``
|
||||
- ``Product2Sequence``
|
||||
@@ -0,0 +1,14 @@
|
||||
# DeprecatedScan
|
||||
|
||||
These methods are deprecated; use the `reductions` family of methods instead.
|
||||
|
||||
See: <doc:Reductions>
|
||||
|
||||
## Topics
|
||||
|
||||
- ``Swift/Sequence/scan(_:)``
|
||||
- ``Swift/Sequence/scan(_:_:)``
|
||||
- ``Swift/Sequence/scan(into:_:)``
|
||||
- ``Swift/LazySequenceProtocol/scan(_:)``
|
||||
- ``Swift/LazySequenceProtocol/scan(_:_:)``
|
||||
- ``Swift/LazySequenceProtocol/scan(into:_:)``
|
||||
@@ -0,0 +1,42 @@
|
||||
# Extending
|
||||
|
||||
Chain two collections end-to-end,
|
||||
or repeat a collection forever or a specific number of times.
|
||||
|
||||
## Overview
|
||||
|
||||
_Chaining_ two collections
|
||||
|
||||
```swift
|
||||
let letters = chain("abcd", "EFGH")
|
||||
// String(letters) == "abcdEFGH"
|
||||
|
||||
for (num, letter) in zip((1...3).cycled(), letters) {
|
||||
print(num, letter)
|
||||
}
|
||||
// 1 a
|
||||
// 2 b
|
||||
// 3 c
|
||||
// 1 d
|
||||
// 2 E
|
||||
// 3 F
|
||||
// 1 G
|
||||
// 2 H
|
||||
```
|
||||
|
||||
## Topics
|
||||
|
||||
### Chaining Two Collections
|
||||
|
||||
- ``chain(_:_:)``
|
||||
|
||||
### Cycling a Collection
|
||||
|
||||
- ``Swift/Collection/cycled()``
|
||||
- ``Swift/Collection/cycled(times:)``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``Chain2Sequence``
|
||||
- ``CycledSequence``
|
||||
- ``CycledTimesCollection``
|
||||
@@ -0,0 +1,41 @@
|
||||
# Filtering
|
||||
|
||||
Remove duplicated elements or strip the `nil` values from a sequence or collection.
|
||||
|
||||
## Overview
|
||||
|
||||
Use the _uniquing_ methods to remove duplicates from a sequence or collection, or to remove elements that have a duplicated property.
|
||||
|
||||
```swift
|
||||
let numbers = [1, 2, 3, 3, 2, 3, 3, 2, 2, 2, 1]
|
||||
|
||||
let unique = numbers.uniqued()
|
||||
// Array(unique) == [1, 2, 3]
|
||||
```
|
||||
|
||||
The `compacted()` method removes all `nil` values from a sequence or collection of optionals:
|
||||
|
||||
```swift
|
||||
let array: [Int?] = [10, nil, 30, nil, 2, 3, nil, 5]
|
||||
let withNoNils = array.compacted()
|
||||
// Array(withNoNils) == [10, 30, 2, 3, 5]
|
||||
```
|
||||
|
||||
## Topics
|
||||
|
||||
### Uniquing Elements
|
||||
|
||||
- ``Swift/Sequence/uniqued()``
|
||||
- ``Swift/Sequence/uniqued(on:)``
|
||||
- ``Swift/LazySequenceProtocol/uniqued(on:)``
|
||||
|
||||
### Filtering out `nil` Elements
|
||||
|
||||
- ``Swift/Collection/compacted()``
|
||||
- ``Swift/Sequence/compacted()``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``UniquedSequence``
|
||||
- ``CompactedSequence``
|
||||
- ``CompactedCollection``
|
||||
@@ -0,0 +1,35 @@
|
||||
# Joining
|
||||
|
||||
Join the parts of a collection of collections,
|
||||
providing a connecting element or collection,
|
||||
or a closure that produces the connector.
|
||||
|
||||
## Topics
|
||||
|
||||
### Joining by an Element
|
||||
|
||||
- ``Swift/Sequence/joined(by:)-6mrf9``
|
||||
- ``Swift/Sequence/joined(by:)-9hyaf``
|
||||
- ``Swift/Collection/joined(by:)-430ue``
|
||||
- ``Swift/LazySequenceProtocol/joined(by:)-3yjw0``
|
||||
- ``Swift/LazySequenceProtocol/joined(by:)-47xvy``
|
||||
|
||||
### Joining by a Collection
|
||||
|
||||
- ``Swift/Sequence/joined(by:)-62j1h``
|
||||
- ``Swift/Sequence/joined(by:)-9b108``
|
||||
- ``Swift/Collection/joined(by:)-28n3b``
|
||||
- ``Swift/LazySequenceProtocol/joined(by:)-4neii``
|
||||
- ``Swift/LazySequenceProtocol/joined(by:)-49xws``
|
||||
|
||||
### Interspersing Elements
|
||||
|
||||
- ``Swift/Sequence/interspersed(with:)``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``JoinedBySequence``
|
||||
- ``JoinedByCollection``
|
||||
- ``JoinedByClosureSequence``
|
||||
- ``JoinedByClosureCollection``
|
||||
- ``InterspersedSequence``
|
||||
@@ -0,0 +1,23 @@
|
||||
# Finding the Minimum and Maximum
|
||||
|
||||
Find the minimum and maximum elements simultaneously,
|
||||
or a specific number of elements at the minimum and maximum.
|
||||
|
||||
## Topics
|
||||
|
||||
### Finding Minimum or Maximum Elements
|
||||
|
||||
- ``Swift/Sequence/min(count:)``
|
||||
- ``Swift/Collection/min(count:)``
|
||||
- ``Swift/Sequence/min(count:sortedBy:)``
|
||||
- ``Swift/Collection/min(count:sortedBy:)``
|
||||
- ``Swift/Sequence/max(count:)``
|
||||
- ``Swift/Collection/max(count:)``
|
||||
- ``Swift/Sequence/max(count:sortedBy:)``
|
||||
- ``Swift/Collection/max(count:sortedBy:)``
|
||||
|
||||
### Finding the Minimum and Maximum Elements Simulataneously
|
||||
|
||||
- ``Swift/Sequence/minAndMax()``
|
||||
- ``Swift/Sequence/minAndMax(by:)``
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
# Partitioning and Rotating
|
||||
|
||||
Partition a collection according to a unary predicate,
|
||||
rotate a collection around a particular index,
|
||||
or find the index where a collection is already partitioned.
|
||||
|
||||
## Overview
|
||||
|
||||
A _stable partition_ maintains the relative order of elements within both partitions.
|
||||
|
||||
```swift
|
||||
// partition(by:) - unstable ordering
|
||||
var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
||||
let p1 = numbers.partition(by: { $0.isMultiple(of: 20) })
|
||||
// p1 == 4
|
||||
// numbers == [10, 70, 30, 50, 40, 60, 20, 80]
|
||||
// ^ start of second partition
|
||||
|
||||
// stablePartition(by:) - maintains relative ordering
|
||||
numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
||||
let p2 = numbers.stablePartition(by: { $0.isMultiple(of: 20) })
|
||||
// p2 == 4
|
||||
// numbers == [10, 30, 50, 70, 20, 40, 60, 80]
|
||||
// ^ start of second partition
|
||||
```
|
||||
|
||||
Use the `rotate` method to shift the elements of a collection to start at a new position, moving the displaced elements to the end:
|
||||
|
||||
```swift
|
||||
var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
||||
let p = numbers.rotate(toStartAt: 2)
|
||||
// numbers == [30, 40, 50, 60, 70, 80, 10, 20]
|
||||
// p == 6 -- numbers[p] == 10
|
||||
```
|
||||
|
||||
## Topics
|
||||
|
||||
### Stable Partition
|
||||
|
||||
- ``Swift/MutableCollection/stablePartition(by:)``
|
||||
- ``Swift/MutableCollection/stablePartition(subrange:by:)``
|
||||
- ``Swift/Sequence/partitioned(by:)``
|
||||
- ``Swift/Collection/partitioned(by:)``
|
||||
|
||||
### Partition of Subranges
|
||||
|
||||
- ``Swift/MutableCollection/partition(subrange:by:)-5vdh7``
|
||||
- ``Swift/MutableCollection/partition(subrange:by:)-4gpqz``
|
||||
|
||||
### Finding a Partition Index
|
||||
|
||||
- ``Swift/Collection/partitioningIndex(where:)``
|
||||
|
||||
### Rotation
|
||||
|
||||
- ``Swift/MutableCollection/rotate(toStartAt:)-9fp48``
|
||||
- ``Swift/MutableCollection/rotate(toStartAt:)-2r55j``
|
||||
- ``Swift/MutableCollection/rotate(subrange:toStartAt:)-ov6a``
|
||||
- ``Swift/MutableCollection/rotate(subrange:toStartAt:)-5teoq``
|
||||
|
||||
### Reversing
|
||||
|
||||
- ``Swift/MutableCollection/reverse(subrange:)``
|
||||
@@ -0,0 +1,35 @@
|
||||
# Reductions
|
||||
|
||||
Find the incremental values of a sequence "reduce" operation.
|
||||
|
||||
## Overview
|
||||
|
||||
Call one of the `reductions` methods when you want the result of a `reduce` operation along with all of its intermediate values:
|
||||
|
||||
```swift
|
||||
let exclusiveRunningTotal = (1...5).reductions(0, +)
|
||||
print(exclusiveRunningTotal)
|
||||
// prints [0, 1, 3, 6, 10, 15]
|
||||
|
||||
let inclusiveRunningTotal = (1...5).reductions(+)
|
||||
print(inclusiveRunningTotal)
|
||||
// prints [1, 3, 6, 10, 15]
|
||||
```
|
||||
|
||||
## Topics
|
||||
|
||||
- ``Swift/Sequence/reductions(_:)``
|
||||
- ``Swift/Sequence/reductions(_:_:)``
|
||||
- ``Swift/Sequence/reductions(into:_:)``
|
||||
- ``Swift/LazySequenceProtocol/reductions(_:)``
|
||||
- ``Swift/LazySequenceProtocol/reductions(_:_:)``
|
||||
- ``Swift/LazySequenceProtocol/reductions(into:_:)``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``InclusiveReductionsSequence``
|
||||
- ``ExclusiveReductionsSequence``
|
||||
|
||||
### Deprecated Methods
|
||||
|
||||
- <doc:DeprecatedScan>
|
||||
@@ -0,0 +1,17 @@
|
||||
# Random Sampling
|
||||
|
||||
Choose a specified number of random elements from a sequence or collection.
|
||||
|
||||
## Topics
|
||||
|
||||
### Random Sampling
|
||||
|
||||
- ``Swift/Sequence/randomSample(count:)``
|
||||
- ``Swift/Collection/randomSample(count:)``
|
||||
- ``Swift/Collection/randomStableSample(count:)``
|
||||
|
||||
### Random Sampling with a Generator
|
||||
|
||||
- ``Swift/Sequence/randomSample(count:using:)``
|
||||
- ``Swift/Collection/randomSample(count:using:)``
|
||||
- ``Swift/Collection/randomStableSample(count:using:)``
|
||||
@@ -0,0 +1,25 @@
|
||||
# Selecting Elements
|
||||
|
||||
Select elements at a particular interval, the first mapped value,
|
||||
or iterate of elements with their indices.
|
||||
|
||||
## Topics
|
||||
|
||||
### Selecting Elements at an Interval
|
||||
|
||||
- ``Swift/Sequence/striding(by:)``
|
||||
- ``Swift/Collection/striding(by:)``
|
||||
|
||||
### Conditionally Finding the First Mapped Value
|
||||
|
||||
- ``Swift/Sequence/firstNonNil(_:)``
|
||||
|
||||
### Iterating Over Elements with Their Indices
|
||||
|
||||
- ``Swift/Collection/indexed()``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``IndexedCollection``
|
||||
- ``StridingSequence``
|
||||
- ``StridingCollection``
|
||||
@@ -0,0 +1,29 @@
|
||||
# Slicing and Splitting
|
||||
|
||||
Iterate over tuple pairs of adjacent elements, overlapping windows of a specified size, or lazily-calculated splits.
|
||||
|
||||
## Topics
|
||||
|
||||
### Adjacent Pairs
|
||||
|
||||
- ``Swift/Sequence/adjacentPairs()``
|
||||
- ``Swift/Collection/adjacentPairs()``
|
||||
|
||||
### Windows
|
||||
|
||||
- ``Swift/Collection/windows(ofCount:)``
|
||||
|
||||
### Lazily Splitting a Collection
|
||||
|
||||
- ``Swift/LazySequenceProtocol/split(separator:maxSplits:omittingEmptySubsequences:)-4q4x8``
|
||||
- ``Swift/LazySequenceProtocol/split(maxSplits:omittingEmptySubsequences:whereSeparator:)-68oqf``
|
||||
- ``Swift/LazySequenceProtocol/split(separator:maxSplits:omittingEmptySubsequences:)-a46s``
|
||||
- ``Swift/LazySequenceProtocol/split(maxSplits:omittingEmptySubsequences:whereSeparator:)-3rwee``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``AdjacentPairsSequence``
|
||||
- ``AdjacentPairsCollection``
|
||||
- ``WindowsOfCountCollection``
|
||||
- ``SplitSequence``
|
||||
- ``SplitCollection``
|
||||
@@ -0,0 +1,27 @@
|
||||
# Trimming
|
||||
|
||||
Remove unwanted elements from the start, the end, or both ends of a collection.
|
||||
|
||||
## Topics
|
||||
|
||||
### Trimming Both Ends of a Collection
|
||||
|
||||
- ``Swift/BidirectionalCollection/trimming(while:)``
|
||||
- ``Swift/BidirectionalCollection/trim(while:)-781az``
|
||||
- ``Swift/BidirectionalCollection/trim(while:)-6cbz3``
|
||||
|
||||
### Trimming from the Start
|
||||
|
||||
- ``Swift/Collection/trimmingPrefix(while:)``
|
||||
- ``Swift/Collection/trimPrefix(while:)-2r8n8``
|
||||
- ``Swift/Collection/trimPrefix(while:)-93obt``
|
||||
|
||||
### Trimming from the End
|
||||
|
||||
- ``Swift/BidirectionalCollection/trimmingSuffix(while:)``
|
||||
- ``Swift/BidirectionalCollection/trimSuffix(while:)-33ubj``
|
||||
- ``Swift/BidirectionalCollection/trimSuffix(while:)-3o6x9``
|
||||
|
||||
### Finding the Suffix of a Collection
|
||||
|
||||
- ``Swift/BidirectionalCollection/suffix(while:)``
|
||||
@@ -0,0 +1,200 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Either
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A general-purpose sum type.
|
||||
@usableFromInline
|
||||
internal enum Either<Left, Right> {
|
||||
case left(Left)
|
||||
case right(Right)
|
||||
}
|
||||
|
||||
extension Either: Equatable where Left: Equatable, Right: Equatable {
|
||||
@usableFromInline
|
||||
internal static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case let (.left(lhs), .left(rhs)):
|
||||
return lhs == rhs
|
||||
case let (.right(lhs), .right(rhs)):
|
||||
return lhs == rhs
|
||||
case (.left, .right), (.right, .left):
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Either: Comparable where Left: Comparable, Right: Comparable {
|
||||
@usableFromInline
|
||||
internal static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case let (.left(lhs), .left(rhs)):
|
||||
return lhs < rhs
|
||||
case let (.right(lhs), .right(rhs)):
|
||||
return lhs < rhs
|
||||
case (.left, .right):
|
||||
return true
|
||||
case (.right, .left):
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// EitherSequence
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A sequence that has one of the two specified types.
|
||||
@usableFromInline
|
||||
internal enum EitherSequence<Left: Sequence, Right: Sequence>
|
||||
where Left.Element == Right.Element
|
||||
{
|
||||
case left(Left)
|
||||
case right(Right)
|
||||
}
|
||||
|
||||
extension EitherSequence: Sequence {
|
||||
@usableFromInline
|
||||
internal struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var left: Left.Iterator?
|
||||
|
||||
@usableFromInline
|
||||
internal var right: Right.Iterator?
|
||||
|
||||
@inlinable
|
||||
internal mutating func next() -> Left.Element? {
|
||||
left?.next() ?? right?.next()
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func makeIterator() -> Iterator {
|
||||
switch self {
|
||||
case .left(let left):
|
||||
return Iterator(left: left.makeIterator(), right: nil)
|
||||
case .right(let right):
|
||||
return Iterator(left: nil, right: right.makeIterator())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension EitherSequence: Collection
|
||||
where Left: Collection, Right: Collection, Left.Element == Right.Element
|
||||
{
|
||||
@usableFromInline
|
||||
internal typealias Index = Either<Left.Index, Right.Index>
|
||||
|
||||
@inlinable
|
||||
internal var startIndex: Index {
|
||||
switch self {
|
||||
case .left(let s):
|
||||
return .left(s.startIndex)
|
||||
case .right(let s):
|
||||
return .right(s.startIndex)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal var endIndex: Index {
|
||||
switch self {
|
||||
case .left(let s):
|
||||
return .left(s.endIndex)
|
||||
case .right(let s):
|
||||
return .right(s.endIndex)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal subscript(position: Index) -> Element {
|
||||
switch (self, position) {
|
||||
case let (.left(s), .left(i)):
|
||||
return s[i]
|
||||
case let (.right(s), .right(i)):
|
||||
return s[i]
|
||||
default:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func index(after i: Index) -> Index {
|
||||
switch (self,i) {
|
||||
case let (.left(s), .left(i)):
|
||||
return .left(s.index(after: i))
|
||||
case let (.right(s), .right(i)):
|
||||
return .right(s.index(after: i))
|
||||
default:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func index(
|
||||
_ i: Index,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
switch (self, i, limit) {
|
||||
case let (.left(s), .left(i), .left(limit)):
|
||||
return s.index(i, offsetBy: distance, limitedBy: limit).map { .left($0) }
|
||||
case let (.right(s), .right(i), .right(limit)):
|
||||
return s.index(i, offsetBy: distance, limitedBy: limit).map { .right($0) }
|
||||
default:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||
switch (self, i) {
|
||||
case let (.left(s), .left(i)):
|
||||
return .left(s.index(i, offsetBy: distance))
|
||||
case let (.right(s), .right(i)):
|
||||
return .right(s.index(i, offsetBy: distance))
|
||||
default:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func distance(from start: Index, to end: Index) -> Int {
|
||||
switch (self, start, end) {
|
||||
case let (.left(s), .left(i), .left(j)):
|
||||
return s.distance(from: i, to: j)
|
||||
case let (.right(s), .right(i), .right(j)):
|
||||
return s.distance(from: i, to: j)
|
||||
default:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension EitherSequence: BidirectionalCollection
|
||||
where Left: BidirectionalCollection, Right: BidirectionalCollection
|
||||
{
|
||||
@inlinable
|
||||
internal func index(before i: Index) -> Index {
|
||||
switch (self, i) {
|
||||
case let (.left(s), .left(i)):
|
||||
return .left(s.index(before: i))
|
||||
case let (.right(s), .right(i)):
|
||||
return .right(s.index(before: i))
|
||||
default:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension EitherSequence: RandomAccessCollection
|
||||
where Left: RandomAccessCollection, Right: RandomAccessCollection {}
|
||||
@@ -13,16 +13,32 @@
|
||||
// firstNonNil(_:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
public extension Sequence {
|
||||
/// Returns the first element in `self` that `transform` maps to a `.some`.
|
||||
func firstNonNil<Result>(
|
||||
extension Sequence {
|
||||
/// Returns the first non-`nil` result obtained from applying the given
|
||||
/// transformation to the elements of the sequence.
|
||||
///
|
||||
/// let strings = ["three", "3.14", "-5", "2"]
|
||||
/// if let firstInt = strings.firstNonNil({ Int($0) }) {
|
||||
/// print(firstInt)
|
||||
/// // -5
|
||||
/// }
|
||||
///
|
||||
/// - Parameter transform: A closure that takes an element of the sequence as
|
||||
/// its argument and returns an optional transformed value.
|
||||
/// - Returns: The first non-`nil` return value of the transformation, or
|
||||
/// `nil` if no transformation is successful.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the number of elements at the start of
|
||||
/// the sequence that result in `nil` when applying the transformation.
|
||||
@inlinable
|
||||
public func firstNonNil<Result>(
|
||||
_ transform: (Element) throws -> Result?
|
||||
) rethrows -> Result? {
|
||||
for value in self {
|
||||
if let value = try transform(value) {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return nil
|
||||
for value in self {
|
||||
if let value = try transform(value) {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A collection consisting of all the elements contained in a collection of
|
||||
/// collections.
|
||||
@usableFromInline
|
||||
internal struct FlattenCollection<Base: Collection>
|
||||
where Base.Element: Collection
|
||||
{
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let indexOfFirstNonEmptyElement: Base.Index
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base) {
|
||||
self.base = base
|
||||
self.indexOfFirstNonEmptyElement = base.endOfPrefix(while: { $0.isEmpty })
|
||||
}
|
||||
}
|
||||
|
||||
extension FlattenCollection: Collection {
|
||||
@usableFromInline
|
||||
internal struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal let outer: Base.Index
|
||||
|
||||
@usableFromInline
|
||||
internal let inner: Base.Element.Index?
|
||||
|
||||
@inlinable
|
||||
init(outer: Base.Index, inner: Base.Element.Index?) {
|
||||
self.outer = outer
|
||||
self.inner = inner
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
guard lhs.outer == rhs.outer else { return lhs.outer < rhs.outer }
|
||||
return lhs.inner == nil ? false : lhs.inner! < rhs.inner!
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal var startIndex: Index {
|
||||
let outer = indexOfFirstNonEmptyElement
|
||||
let inner = outer == base.endIndex ? nil : base[outer].startIndex
|
||||
return Index(outer: outer, inner: inner)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal var endIndex: Index {
|
||||
Index(outer: base.endIndex, inner: nil)
|
||||
}
|
||||
|
||||
/// Forms an index from a pair of base indices, normalizing
|
||||
/// `(i, base2.endIndex)` to `(base1.index(after: i), base2.startIndex)` if
|
||||
/// necessary.
|
||||
@inlinable
|
||||
internal func normalizeIndex(
|
||||
outer: Base.Index,
|
||||
inner: Base.Element.Index
|
||||
) -> Index {
|
||||
if inner == base[outer].endIndex {
|
||||
let outer = base[base.index(after: outer)...]
|
||||
.endOfPrefix(while: { $0.isEmpty })
|
||||
let inner = outer == base.endIndex ? nil : base[outer].startIndex
|
||||
return Index(outer: outer, inner: inner)
|
||||
} else {
|
||||
return Index(outer: outer, inner: inner)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func index(after index: Index) -> Index {
|
||||
let element = base[index.outer]
|
||||
let nextInner = element.index(after: index.inner!)
|
||||
return normalizeIndex(outer: index.outer, inner: nextInner)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal subscript(position: Index) -> Base.Element.Element {
|
||||
base[position.outer][position.inner!]
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func distance(from start: Index, to end: Index) -> Int {
|
||||
guard start.outer <= end.outer
|
||||
else { return -distance(from: end, to: start) }
|
||||
guard let startInner = start.inner
|
||||
else { return 0 }
|
||||
guard start.outer != end.outer
|
||||
else {
|
||||
return base[start.outer].distance(from: startInner, to: end.inner!)
|
||||
}
|
||||
|
||||
let firstPart = base[start.outer][startInner...].count
|
||||
let middlePart = base[start.outer..<end.outer].dropFirst()
|
||||
.reduce(0, { $0 + $1.count })
|
||||
let lastPart = end.inner.map { base[end.outer][..<$0].count } ?? 0
|
||||
|
||||
return firstPart + middlePart + lastPart
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func index(_ index: Index, offsetBy distance: Int) -> Index {
|
||||
guard distance != 0 else { return index }
|
||||
|
||||
return distance > 0
|
||||
? offsetForward(index, by: distance)
|
||||
: offsetBackward(index, by: -distance)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func index(
|
||||
_ index: Index,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
guard distance != 0 else { return index }
|
||||
|
||||
if distance > 0 {
|
||||
return limit >= index
|
||||
? offsetForward(index, by: distance, limitedBy: limit)
|
||||
: offsetForward(index, by: distance)
|
||||
} else {
|
||||
return limit <= index
|
||||
? offsetBackward(index, by: -distance, limitedBy: limit)
|
||||
: offsetBackward(index, by: -distance)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
|
||||
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
|
||||
else { fatalError("Index is out of bounds") }
|
||||
return index
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
|
||||
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
|
||||
else { fatalError("Index is out of bounds") }
|
||||
return index
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(
|
||||
_ index: Index, by distance: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance > 0)
|
||||
assert(limit >= index)
|
||||
|
||||
if index.outer == limit.outer {
|
||||
if let indexInner = index.inner, let limitInner = limit.inner {
|
||||
return base[index.outer]
|
||||
.index(indexInner, offsetBy: distance, limitedBy: limitInner)
|
||||
.map { inner in Index(outer: index.outer, inner: inner) }
|
||||
} else {
|
||||
// `index` and `limit` are both `endIndex`
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// `index <= limit` and `index.outer != limit.outer`, so `index != endIndex`
|
||||
let indexInner = index.inner!
|
||||
let element = base[index.outer]
|
||||
|
||||
if let inner = element.index(
|
||||
indexInner,
|
||||
offsetBy: distance,
|
||||
limitedBy: element.endIndex
|
||||
) {
|
||||
return normalizeIndex(outer: index.outer, inner: inner)
|
||||
}
|
||||
|
||||
var remainder = distance - element[indexInner...].count
|
||||
var outer = base.index(after: index.outer)
|
||||
|
||||
while outer != limit.outer {
|
||||
let element = base[outer]
|
||||
|
||||
if let inner = element.index(
|
||||
element.startIndex,
|
||||
offsetBy: remainder,
|
||||
limitedBy: element.endIndex
|
||||
) {
|
||||
return normalizeIndex(outer: outer, inner: inner)
|
||||
}
|
||||
|
||||
remainder -= element.count
|
||||
base.formIndex(after: &outer)
|
||||
}
|
||||
|
||||
if let limitInner = limit.inner {
|
||||
let element = base[outer]
|
||||
return element.index(
|
||||
element.startIndex,
|
||||
offsetBy: remainder,
|
||||
limitedBy: limitInner)
|
||||
.map { inner in Index(outer: outer, inner: inner) }
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(
|
||||
_ index: Index, by distance: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance > 0)
|
||||
assert(limit <= index)
|
||||
|
||||
if index.outer == limit.outer {
|
||||
if let indexInner = index.inner, let limitInner = limit.inner {
|
||||
return base[index.outer]
|
||||
.index(indexInner, offsetBy: -distance, limitedBy: limitInner)
|
||||
.map { inner in Index(outer: index.outer, inner: inner) }
|
||||
} else {
|
||||
// `index` and `limit` are both `endIndex`
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
var remainder = distance
|
||||
|
||||
if let indexInner = index.inner {
|
||||
let element = base[index.outer]
|
||||
|
||||
if let inner = element.index(
|
||||
indexInner,
|
||||
offsetBy: -remainder,
|
||||
limitedBy: element.startIndex
|
||||
) {
|
||||
return Index(outer: index.outer, inner: inner)
|
||||
}
|
||||
|
||||
remainder -= element[..<indexInner].count
|
||||
}
|
||||
|
||||
var outer = base.index(index.outer, offsetBy: -1)
|
||||
|
||||
while outer != limit.outer {
|
||||
let element = base[outer]
|
||||
|
||||
if let inner = element.index(
|
||||
element.endIndex,
|
||||
offsetBy: -remainder,
|
||||
limitedBy: element.startIndex
|
||||
) {
|
||||
return Index(outer: outer, inner: inner)
|
||||
}
|
||||
|
||||
remainder -= element.count
|
||||
base.formIndex(&outer, offsetBy: -1)
|
||||
}
|
||||
|
||||
let element = base[outer]
|
||||
return element.index(
|
||||
element.endIndex,
|
||||
offsetBy: -remainder,
|
||||
limitedBy: limit.inner!
|
||||
).map { inner in Index(outer: outer, inner: inner) }
|
||||
}
|
||||
}
|
||||
|
||||
extension FlattenCollection: BidirectionalCollection
|
||||
where Base: BidirectionalCollection, Base.Element: BidirectionalCollection
|
||||
{
|
||||
@inlinable
|
||||
internal func index(before index: Index) -> Index {
|
||||
if let inner = index.inner {
|
||||
let element = base[index.outer]
|
||||
|
||||
if inner != element.startIndex {
|
||||
let previousInner = element.index(before: inner)
|
||||
return Index(outer: index.outer, inner: previousInner)
|
||||
}
|
||||
}
|
||||
|
||||
let previousOuter = base[..<index.outer].lastIndex(where: { !$0.isEmpty })!
|
||||
let element = base[previousOuter]
|
||||
let previousInner = element.index(before: element.endIndex)
|
||||
return Index(outer: previousOuter, inner: previousInner)
|
||||
}
|
||||
}
|
||||
|
||||
extension FlattenCollection: LazySequenceProtocol, LazyCollectionProtocol
|
||||
where Base: LazySequenceProtocol, Base.Element: LazySequenceProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// joined()
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Collection where Element: Collection {
|
||||
/// Returns the concatenation of the elements in this collection of
|
||||
/// collections.
|
||||
@inlinable
|
||||
internal func joined() -> FlattenCollection<Self> {
|
||||
FlattenCollection(base: self)
|
||||
}
|
||||
}
|
||||
@@ -11,12 +11,10 @@
|
||||
|
||||
/// A collection wrapper that iterates over the indices and elements of a
|
||||
/// collection together.
|
||||
public struct Indexed<Base: Collection> {
|
||||
/// The element type for an `Indexed` collection.
|
||||
public typealias Element = (index: Base.Index, element: Base.Element)
|
||||
|
||||
public struct IndexedCollection<Base: Collection> {
|
||||
/// The base collection.
|
||||
public let base: Base
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base) {
|
||||
@@ -24,7 +22,10 @@ public struct Indexed<Base: Collection> {
|
||||
}
|
||||
}
|
||||
|
||||
extension Indexed: Collection {
|
||||
extension IndexedCollection: Collection {
|
||||
/// The element type for an `IndexedCollection` collection.
|
||||
public typealias Element = (index: Base.Index, element: Base.Element)
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Base.Index {
|
||||
base.startIndex
|
||||
@@ -51,7 +52,11 @@ extension Indexed: Collection {
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Base.Index, offsetBy distance: Int, limitedBy limit: Base.Index) -> Base.Index? {
|
||||
public func index(
|
||||
_ i: Base.Index,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Base.Index
|
||||
) -> Base.Index? {
|
||||
base.index(i, offsetBy: distance, limitedBy: limit)
|
||||
}
|
||||
|
||||
@@ -59,20 +64,27 @@ extension Indexed: Collection {
|
||||
public func distance(from start: Base.Index, to end: Base.Index) -> Int {
|
||||
base.distance(from: start, to: end)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var indices: Base.Indices {
|
||||
base.indices
|
||||
}
|
||||
}
|
||||
|
||||
extension Indexed: BidirectionalCollection where Base: BidirectionalCollection {
|
||||
extension IndexedCollection: BidirectionalCollection
|
||||
where Base: BidirectionalCollection
|
||||
{
|
||||
@inlinable
|
||||
public func index(before i: Base.Index) -> Base.Index {
|
||||
base.index(before: i)
|
||||
}
|
||||
}
|
||||
|
||||
extension Indexed: RandomAccessCollection where Base: RandomAccessCollection {}
|
||||
extension Indexed: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
extension Indexed: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
|
||||
extension Indexed: Equatable where Base: Equatable {}
|
||||
extension Indexed: Hashable where Base: Hashable {}
|
||||
extension IndexedCollection: RandomAccessCollection
|
||||
where Base: RandomAccessCollection {}
|
||||
|
||||
extension IndexedCollection: LazySequenceProtocol, LazyCollectionProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// indexed()
|
||||
@@ -82,6 +94,10 @@ extension Collection {
|
||||
/// Returns a collection of pairs *(i, x)*, where *i* represents an index of
|
||||
/// the collection, and *x* represents an element.
|
||||
///
|
||||
/// The `indexed()` method is similar to the standard library's `enumerated()`
|
||||
/// method, but provides the index with each element instead of a zero-based
|
||||
/// counter.
|
||||
///
|
||||
/// This example iterates over the indices and elements of a set, building an
|
||||
/// array consisting of indices of names with five or fewer letters.
|
||||
///
|
||||
@@ -93,9 +109,9 @@ extension Collection {
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// Returns: A collection of paired indices and elements of this collection.
|
||||
/// - Returns: A collection of paired indices and elements of this collection.
|
||||
@inlinable
|
||||
public func indexed() -> Indexed<Self> {
|
||||
Indexed(base: self)
|
||||
public func indexed() -> IndexedCollection<Self> {
|
||||
IndexedCollection(base: self)
|
||||
}
|
||||
}
|
||||
@@ -9,9 +9,13 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A sequence that presents the elements of a base sequence of elements
|
||||
/// with a separator between each of those elements.
|
||||
public struct Intersperse<Base: Sequence> {
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Intersperse
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A sequence that presents the elements of a base sequence of elements with a
|
||||
/// separator between each of those elements.
|
||||
public struct InterspersedSequence<Base: Sequence> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@@ -25,9 +29,16 @@ public struct Intersperse<Base: Sequence> {
|
||||
}
|
||||
}
|
||||
|
||||
extension Intersperse: Sequence {
|
||||
/// The iterator for an `Intersperse` sequence.
|
||||
extension InterspersedSequence: Sequence {
|
||||
/// The iterator for an `InterspersedSequence` sequence.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal enum State {
|
||||
case start
|
||||
case element(Base.Element)
|
||||
case separator
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal var iterator: Base.Iterator
|
||||
|
||||
@@ -42,13 +53,6 @@ extension Intersperse: Sequence {
|
||||
self.iterator = iterator
|
||||
self.separator = separator
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
enum State {
|
||||
case start
|
||||
case element(Base.Element)
|
||||
case separator
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Base.Element? {
|
||||
@@ -72,16 +76,16 @@ extension Intersperse: Sequence {
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Intersperse<Base>.Iterator {
|
||||
public func makeIterator() -> InterspersedSequence<Base>.Iterator {
|
||||
Iterator(iterator: base.makeIterator(), separator: separator)
|
||||
}
|
||||
}
|
||||
|
||||
extension Intersperse: Collection where Base: Collection {
|
||||
/// A position in an `Intersperse` collection.
|
||||
extension InterspersedSequence: Collection where Base: Collection {
|
||||
/// A position in an `InterspersedSequence` instance.
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
enum Representation: Equatable {
|
||||
internal enum Representation: Equatable {
|
||||
case element(Base.Index)
|
||||
case separator(next: Base.Index)
|
||||
}
|
||||
@@ -90,7 +94,7 @@ extension Intersperse: Collection where Base: Collection {
|
||||
internal let representation: Representation
|
||||
|
||||
@inlinable
|
||||
init(representation: Representation) {
|
||||
internal init(representation: Representation) {
|
||||
self.representation = representation
|
||||
}
|
||||
|
||||
@@ -107,12 +111,12 @@ extension Intersperse: Collection where Base: Collection {
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func element(_ index: Base.Index) -> Self {
|
||||
internal static func element(_ index: Base.Index) -> Self {
|
||||
Self(representation: .element(index))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func separator(next: Base.Index) -> Self {
|
||||
internal static func separator(next: Base.Index) -> Self {
|
||||
Self(representation: .separator(next: next))
|
||||
}
|
||||
}
|
||||
@@ -146,21 +150,6 @@ extension Intersperse: Collection where Base: Collection {
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||
switch (i.representation, distance.isMultiple(of: 2)) {
|
||||
case (let .element(index), true):
|
||||
return .element(base.index(index, offsetBy: distance / 2))
|
||||
case (let .element(index), false):
|
||||
return .separator(next: base.index(index, offsetBy: (distance + 1) / 2))
|
||||
case (let .separator(next: index), true):
|
||||
return .separator(next: base.index(index, offsetBy: distance / 2))
|
||||
case (let .separator(next: index), false):
|
||||
return .element(base.index(index, offsetBy: (distance - 1) / 2))
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Implement index(_:offsetBy:limitedBy:)
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
switch (start.representation, end.representation) {
|
||||
@@ -173,9 +162,101 @@ extension Intersperse: Collection where Base: Collection {
|
||||
return 2 * base.distance(from: start, to: end)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ index: Index, offsetBy distance: Int) -> Index {
|
||||
distance >= 0
|
||||
? offsetForward(index, by: distance)
|
||||
: offsetBackward(index, by: -distance)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(
|
||||
_ index: Index,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
if distance >= 0 {
|
||||
return limit >= index
|
||||
? offsetForward(index, by: distance, limitedBy: limit)
|
||||
: offsetForward(index, by: distance)
|
||||
} else {
|
||||
return limit <= index
|
||||
? offsetBackward(index, by: -distance, limitedBy: limit)
|
||||
: offsetBackward(index, by: -distance)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
|
||||
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
|
||||
else { fatalError("Index is out of bounds") }
|
||||
return index
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
|
||||
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
|
||||
else { fatalError("Index is out of bounds") }
|
||||
return index
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(
|
||||
_ index: Index, by distance: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance >= 0)
|
||||
assert(limit >= index)
|
||||
|
||||
switch (index.representation, limit.representation, distance.isMultiple(of: 2)) {
|
||||
case let (.element(index), .element(limit), true),
|
||||
let (.separator(next: index), .element(limit), false):
|
||||
return base.index(index, offsetBy: distance / 2, limitedBy: limit)
|
||||
.map { .element($0) }
|
||||
|
||||
case let (.element(index), .element(limit), false),
|
||||
let (.element(index), .separator(next: limit), false),
|
||||
let (.separator(next: index), .element(limit), true),
|
||||
let (.separator(next: index), .separator(next: limit), true):
|
||||
return base.index(index, offsetBy: (distance + 1) / 2, limitedBy: limit)
|
||||
.map { .separator(next: $0) }
|
||||
|
||||
case let (.element(index), .separator(next: limit), true),
|
||||
let (.separator(next: index), .separator(next: limit), false):
|
||||
return base.index(index, offsetBy: distance / 2, limitedBy: limit)
|
||||
.flatMap { $0 == limit ? nil : .element($0) }
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(
|
||||
_ index: Index, by distance: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance >= 0)
|
||||
assert(limit <= index)
|
||||
|
||||
switch (index.representation, limit.representation, distance.isMultiple(of: 2)) {
|
||||
case let (.element(index), .element(limit), true),
|
||||
let (.element(index), .separator(next: limit), true),
|
||||
let (.separator(next: index), .element(limit), false),
|
||||
let (.separator(next: index), .separator(next: limit), false):
|
||||
return base.index(index, offsetBy: -((distance + 1) / 2), limitedBy: limit)
|
||||
.map { .element($0) }
|
||||
|
||||
case let (.element(index), .separator(next: limit), false),
|
||||
let (.separator(next: index), .separator(next: limit), true):
|
||||
return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)
|
||||
.map { .separator(next: $0) }
|
||||
|
||||
case let (.element(index), .element(limit), false),
|
||||
let (.separator(next: index), .element(limit), true):
|
||||
return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)
|
||||
.flatMap { $0 == limit ? nil : .separator(next: $0) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Intersperse: BidirectionalCollection
|
||||
extension InterspersedSequence: BidirectionalCollection
|
||||
where Base: BidirectionalCollection
|
||||
{
|
||||
@inlinable
|
||||
@@ -190,17 +271,337 @@ extension Intersperse: BidirectionalCollection
|
||||
}
|
||||
}
|
||||
|
||||
extension Intersperse: RandomAccessCollection
|
||||
extension InterspersedSequence: RandomAccessCollection
|
||||
where Base: RandomAccessCollection {}
|
||||
|
||||
extension Intersperse: LazySequenceProtocol
|
||||
extension InterspersedSequence: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
extension Intersperse: LazyCollectionProtocol
|
||||
where Base: LazyCollectionProtocol {}
|
||||
extension InterspersedSequence: LazyCollectionProtocol
|
||||
where Base: LazySequenceProtocol & Collection {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// InterspersedMap
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
|
||||
/// A sequence over the results of applying a closure to the sequence's
|
||||
/// elements, with a separator that separates each pair of adjacent transformed
|
||||
/// values.
|
||||
@usableFromInline
|
||||
internal struct InterspersedMapSequence<Base: Sequence, Result> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let transform: (Base.Element) -> Result
|
||||
|
||||
@usableFromInline
|
||||
internal let separator: (Base.Element, Base.Element) -> Result
|
||||
}
|
||||
|
||||
extension InterspersedMapSequence: Sequence {
|
||||
@usableFromInline
|
||||
internal struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal enum State {
|
||||
case start
|
||||
case element(Base.Element)
|
||||
case separator(previous: Base.Element)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal var base: Base.Iterator
|
||||
|
||||
@usableFromInline
|
||||
internal let transform: (Base.Element) -> Result
|
||||
|
||||
@usableFromInline
|
||||
internal let separator: (Base.Element, Base.Element) -> Result
|
||||
|
||||
@usableFromInline
|
||||
internal var state = State.start
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
base: Base.Iterator,
|
||||
transform: @escaping (Base.Element) -> Result,
|
||||
separator: @escaping (Base.Element, Base.Element) -> Result
|
||||
) {
|
||||
self.base = base
|
||||
self.transform = transform
|
||||
self.separator = separator
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal mutating func next() -> Result? {
|
||||
switch state {
|
||||
case .start:
|
||||
guard let first = base.next() else { return nil }
|
||||
state = .separator(previous: first)
|
||||
return transform(first)
|
||||
case .separator(let previous):
|
||||
guard let next = base.next() else { return nil }
|
||||
state = .element(next)
|
||||
return separator(previous, next)
|
||||
case .element(let element):
|
||||
state = .separator(previous: element)
|
||||
return transform(element)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func makeIterator() -> Iterator {
|
||||
Iterator(
|
||||
base: base.makeIterator(),
|
||||
transform: transform,
|
||||
separator: separator)
|
||||
}
|
||||
}
|
||||
|
||||
extension InterspersedMapSequence: Collection where Base: Collection {
|
||||
@usableFromInline
|
||||
internal struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal enum Representation {
|
||||
case element(Base.Index)
|
||||
case separator(previous: Base.Index, next: Base.Index)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal let representation: Representation
|
||||
|
||||
@inlinable
|
||||
internal init(representation: Representation) {
|
||||
self.representation = representation
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal static func element(_ index: Base.Index) -> Self {
|
||||
Self(representation: .element(index))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal static func separator(previous: Base.Index, next: Base.Index) -> Self {
|
||||
Self(representation: .separator(previous: previous, next: next))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
switch (lhs.representation, rhs.representation) {
|
||||
case let (.element(lhs), .element(rhs)),
|
||||
let (.separator(_, next: lhs), .separator(_, next: rhs)):
|
||||
return lhs == rhs
|
||||
case (.element, .separator), (.separator, .element):
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
switch (lhs.representation, rhs.representation) {
|
||||
case let (.element(lhs), .element(rhs)),
|
||||
let (.separator(_, next: lhs), .separator(_, next: rhs)),
|
||||
let (.element(lhs), .separator(_, next: rhs)),
|
||||
let (.separator(previous: lhs, _), .element(rhs)):
|
||||
return lhs < rhs
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal var startIndex: Index {
|
||||
base.isEmpty ? endIndex : .element(base.startIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal var endIndex: Index {
|
||||
.separator(previous: base.endIndex, next: base.endIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func index(after index: Index) -> Index {
|
||||
switch index.representation {
|
||||
case .element(let index):
|
||||
let next = base.index(after: index)
|
||||
return .separator(previous: index, next: next)
|
||||
case .separator(_, let next):
|
||||
return .element(next)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal subscript(position: Index) -> Result {
|
||||
switch position.representation {
|
||||
case .element(let index):
|
||||
return transform(base[index])
|
||||
case let .separator(previous, next):
|
||||
return separator(base[previous], base[next])
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func distance(from start: Index, to end: Index) -> Int {
|
||||
switch (start.representation, end.representation) {
|
||||
case let (.element(lhs), .element(rhs)),
|
||||
let (.separator(_, next: lhs), .separator(_, next: rhs)):
|
||||
return 2 * base.distance(from: lhs, to: rhs)
|
||||
case let (.element(lhs), .separator(_, next: rhs)):
|
||||
return 2 * base.distance(from: lhs, to: rhs) - 1
|
||||
case let (.separator(_, next: lhs), .element(rhs)):
|
||||
return 2 * base.distance(from: lhs, to: rhs) + 1
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func index(_ index: Index, offsetBy distance: Int) -> Index {
|
||||
guard distance != 0 else { return index }
|
||||
|
||||
return distance > 0
|
||||
? offsetForward(index, by: distance)
|
||||
: offsetBackward(index, by: -distance)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func index(
|
||||
_ index: Index,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
guard distance != 0 else { return index }
|
||||
|
||||
if distance > 0 {
|
||||
return limit >= index
|
||||
? offsetForward(index, by: distance, limitedBy: limit)
|
||||
: offsetForward(index, by: distance)
|
||||
} else {
|
||||
return limit <= index
|
||||
? offsetBackward(index, by: -distance, limitedBy: limit)
|
||||
: offsetBackward(index, by: -distance)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
|
||||
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
|
||||
else { fatalError("Index is out of bounds") }
|
||||
return index
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
|
||||
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
|
||||
else { fatalError("Index is out of bounds") }
|
||||
return index
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetForward(
|
||||
_ index: Index, by distance: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance > 0)
|
||||
assert(limit >= index)
|
||||
|
||||
switch (index.representation, limit.representation, distance.isMultiple(of: 2)) {
|
||||
case let (.element(index), .element(limit), true),
|
||||
let (.separator(_, next: index), .element(limit), false):
|
||||
return base.index(index, offsetBy: distance / 2, limitedBy: limit)
|
||||
.map { .element($0) }
|
||||
|
||||
case let (.element(index), .element(limit), false),
|
||||
let (.element(index), .separator(_, next: limit), false),
|
||||
let (.separator(_, next: index), .element(limit), true),
|
||||
let (.separator(_, next: index), .separator(_, next: limit), true):
|
||||
return base.index(index, offsetBy: (distance - 1) / 2, limitedBy: limit)
|
||||
.flatMap {
|
||||
guard $0 != limit else { return nil }
|
||||
let next = base.index(after: $0)
|
||||
return next == base.endIndex
|
||||
? endIndex
|
||||
: .separator(previous: $0, next: next)
|
||||
}
|
||||
|
||||
case let (.element(index), .separator(_, next: limit), true),
|
||||
let (.separator(_, next: index), .separator(_, next: limit), false):
|
||||
return base.index(index, offsetBy: distance / 2, limitedBy: limit)
|
||||
.flatMap { $0 == limit ? nil : .element($0) }
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func offsetBackward(
|
||||
_ index: Index, by distance: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
assert(distance > 0)
|
||||
assert(limit <= index)
|
||||
|
||||
switch (index.representation, limit.representation, distance.isMultiple(of: 2)) {
|
||||
case let (.element(index), .element(limit), true),
|
||||
let (.element(index), .separator(_, next: limit), true),
|
||||
let (.separator(_, next: index), .element(limit), false),
|
||||
let (.separator(_, next: index), .separator(_, next: limit), false):
|
||||
return base.index(index, offsetBy: -((distance + 1) / 2), limitedBy: limit)
|
||||
.map { .element($0) }
|
||||
|
||||
case let (.element(index), .separator(_, next: limit), false),
|
||||
let (.separator(_, next: index), .separator(_, next: limit), true):
|
||||
return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)
|
||||
.map { .separator(previous: base.index($0, offsetBy: -1), next: $0) }
|
||||
|
||||
case let (.element(index), .element(limit), false),
|
||||
let (.separator(_, next: index), .element(limit), true):
|
||||
return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)
|
||||
.flatMap {
|
||||
$0 == limit
|
||||
? nil
|
||||
: .separator(previous: base.index($0, offsetBy: -1), next: $0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension InterspersedMapSequence: BidirectionalCollection
|
||||
where Base: BidirectionalCollection
|
||||
{
|
||||
@inlinable
|
||||
internal func index(before index: Index) -> Index {
|
||||
switch index.representation {
|
||||
case .element(let index):
|
||||
let previous = base.index(before: index)
|
||||
return .separator(previous: previous, next: index)
|
||||
case let .separator(previous, next):
|
||||
let index = next == base.endIndex ? base.index(before: next) : previous
|
||||
return .element(index)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension InterspersedMapSequence.Index: Hashable
|
||||
where Base.Index: Hashable
|
||||
{
|
||||
@inlinable
|
||||
internal func hash(into hasher: inout Hasher) {
|
||||
switch representation {
|
||||
case .element(let base):
|
||||
hasher.combine(false)
|
||||
hasher.combine(base)
|
||||
case .separator(_, let next):
|
||||
hasher.combine(true)
|
||||
hasher.combine(next)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension InterspersedMapSequence: LazySequenceProtocol {}
|
||||
extension InterspersedMapSequence: LazyCollectionProtocol
|
||||
where Base: Collection {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// interspersed(with:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Sequence {
|
||||
|
||||
/// Returns a sequence containing elements of this sequence with the given
|
||||
/// separator inserted in between each element.
|
||||
///
|
||||
@@ -230,7 +631,39 @@ extension Sequence {
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func interspersed(with separator: Element) -> Intersperse<Self> {
|
||||
Intersperse(base: self, separator: separator)
|
||||
public func interspersed(
|
||||
with separator: Element
|
||||
) -> InterspersedSequence<Self> {
|
||||
InterspersedSequence(base: self, separator: separator)
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// lazy.interspersedMap(_:with:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension LazySequenceProtocol {
|
||||
/// Returns a sequence over the results of applying a closure to the
|
||||
/// sequence's elements, with a separator that separates each pair of adjacent
|
||||
/// transformed values.
|
||||
///
|
||||
/// The transformation closure lets you intersperse a sequence using a
|
||||
/// separator of a different type than the original's sequence's elements.
|
||||
/// Each separator is produced by a closure that is given access to the
|
||||
/// two elements in the original sequence right before and after it.
|
||||
///
|
||||
/// let strings = [1, 2, 2].interspersedMap(String.init,
|
||||
/// with: { $0 == $1 ? " == " : " != " })
|
||||
/// print(strings.joined()) // "1 != 2 == 2"
|
||||
///
|
||||
@usableFromInline
|
||||
internal func interspersedMap<Result>(
|
||||
_ transform: @escaping (Element) -> Result,
|
||||
with separator: @escaping (Element, Element) -> Result
|
||||
) -> InterspersedMapSequence<Elements, Result> {
|
||||
InterspersedMapSequence(
|
||||
base: elements,
|
||||
transform: transform,
|
||||
separator: separator)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,489 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// JoinedBySequence
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A sequence that presents the elements of a base sequence of sequences
|
||||
/// concatenated using a given separator.
|
||||
public struct JoinedBySequence<Base: Sequence, Separator: Sequence>
|
||||
where Base.Element: Sequence, Base.Element.Element == Separator.Element
|
||||
{
|
||||
@usableFromInline
|
||||
internal typealias Inner = FlattenSequence<InterspersedSequence<
|
||||
LazyMapSequence<Base, EitherSequence<Base.Element, Separator>>>>
|
||||
|
||||
@usableFromInline
|
||||
internal let inner: Inner
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base, separator: Separator) {
|
||||
self.inner = base.lazy
|
||||
.map(EitherSequence.left)
|
||||
.interspersed(with: .right(separator))
|
||||
.joined()
|
||||
}
|
||||
}
|
||||
|
||||
extension JoinedBySequence: Sequence {
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var inner: Inner.Iterator
|
||||
|
||||
@inlinable
|
||||
internal init(inner: Inner.Iterator) {
|
||||
self.inner = inner
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Base.Element.Element? {
|
||||
inner.next()
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(inner: inner.makeIterator())
|
||||
}
|
||||
}
|
||||
|
||||
extension JoinedBySequence: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// JoinedByClosureSequence
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A sequence that presents the elements of a base sequence of sequences
|
||||
/// concatenated using a given separator that depends on the sequences right
|
||||
/// before and after it.
|
||||
public struct JoinedByClosureSequence<Base: Sequence, Separator: Sequence>
|
||||
where Base.Element: Sequence, Base.Element.Element == Separator.Element
|
||||
{
|
||||
@usableFromInline
|
||||
internal typealias Inner = FlattenSequence<InterspersedMapSequence<
|
||||
Base, EitherSequence<Base.Element, Separator>>>
|
||||
|
||||
@usableFromInline
|
||||
internal let inner: Inner
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
base: Base,
|
||||
separator: @escaping (Base.Element, Base.Element) -> Separator
|
||||
) {
|
||||
self.inner = base.lazy
|
||||
.interspersedMap(
|
||||
EitherSequence.left,
|
||||
with: { EitherSequence.right(separator($0, $1)) })
|
||||
.joined()
|
||||
}
|
||||
}
|
||||
|
||||
extension JoinedByClosureSequence: Sequence {
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var inner: Inner.Iterator
|
||||
|
||||
@inlinable
|
||||
internal init(inner: Inner.Iterator) {
|
||||
self.inner = inner
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Base.Element.Element? {
|
||||
inner.next()
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(inner: inner.makeIterator())
|
||||
}
|
||||
}
|
||||
|
||||
extension JoinedByClosureSequence: LazySequenceProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// JoinedByCollection
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A collection that presents the elements of a base collection of collections
|
||||
/// concatenated using a given separator.
|
||||
public struct JoinedByCollection<Base: Collection, Separator: Collection>
|
||||
where Base.Element: Collection, Base.Element.Element == Separator.Element
|
||||
{
|
||||
@usableFromInline
|
||||
internal typealias Inner = FlattenCollection<InterspersedSequence<
|
||||
LazyMapSequence<Base, EitherSequence<Base.Element, Separator>>>>
|
||||
|
||||
@usableFromInline
|
||||
internal let inner: Inner
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base, separator: Separator) {
|
||||
self.inner = base.lazy
|
||||
.map(EitherSequence.left)
|
||||
.interspersed(with: .right(separator))
|
||||
.joined()
|
||||
}
|
||||
}
|
||||
|
||||
extension JoinedByCollection: Collection {
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal let inner: Inner.Index
|
||||
|
||||
@inlinable
|
||||
internal init(_ inner: Inner.Index) {
|
||||
self.inner = inner
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.inner == rhs.inner
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.inner < rhs.inner
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
Index(inner.startIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
Index(inner.endIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after index: Index) -> Index {
|
||||
Index(inner.index(after: index.inner))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> Base.Element.Element {
|
||||
inner[position.inner]
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ index: Index, offsetBy distance: Int) -> Index {
|
||||
Index(inner.index(index.inner, offsetBy: distance))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(
|
||||
_ index: Index,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
inner.index(index.inner, offsetBy: distance, limitedBy: limit.inner)
|
||||
.map(Index.init)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
inner.distance(from: start.inner, to: end.inner)
|
||||
}
|
||||
}
|
||||
|
||||
extension JoinedByCollection: BidirectionalCollection
|
||||
where Base: BidirectionalCollection,
|
||||
Base.Element: BidirectionalCollection,
|
||||
Separator: BidirectionalCollection
|
||||
{
|
||||
@inlinable
|
||||
public func index(before index: Index) -> Index {
|
||||
Index(inner.index(before: index.inner))
|
||||
}
|
||||
}
|
||||
|
||||
extension JoinedByCollection: LazySequenceProtocol, LazyCollectionProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// JoinedByClosureCollection
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A collection that presents the elements of a base collection of collections
|
||||
/// concatenated using a given separator that depends on the collections right
|
||||
/// before and after it.
|
||||
public struct JoinedByClosureCollection<Base: Collection, Separator: Collection>
|
||||
where Base.Element: Collection, Base.Element.Element == Separator.Element
|
||||
{
|
||||
@usableFromInline
|
||||
internal typealias Inner = FlattenCollection<InterspersedMapSequence<
|
||||
Base, EitherSequence<Base.Element, Separator>>>
|
||||
|
||||
@usableFromInline
|
||||
internal let inner: Inner
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
base: Base,
|
||||
separator: @escaping (Base.Element, Base.Element) -> Separator
|
||||
) {
|
||||
self.inner = base.lazy
|
||||
.interspersedMap(
|
||||
EitherSequence.left,
|
||||
with: { EitherSequence.right(separator($0, $1)) })
|
||||
.joined()
|
||||
}
|
||||
}
|
||||
|
||||
extension JoinedByClosureCollection: Collection {
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal let inner: Inner.Index
|
||||
|
||||
@inlinable
|
||||
internal init(_ inner: Inner.Index) {
|
||||
self.inner = inner
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.inner == rhs.inner
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.inner < rhs.inner
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
Index(inner.startIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
Index(inner.endIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after index: Index) -> Index {
|
||||
Index(inner.index(after: index.inner))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> Base.Element.Element {
|
||||
inner[position.inner]
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ index: Index, offsetBy distance: Int) -> Index {
|
||||
Index(inner.index(index.inner, offsetBy: distance))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(
|
||||
_ index: Index,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
inner.index(index.inner, offsetBy: distance, limitedBy: limit.inner)
|
||||
.map(Index.init)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
inner.distance(from: start.inner, to: end.inner)
|
||||
}
|
||||
}
|
||||
|
||||
extension JoinedByClosureCollection: BidirectionalCollection
|
||||
where Base: BidirectionalCollection,
|
||||
Base.Element: BidirectionalCollection,
|
||||
Separator: BidirectionalCollection
|
||||
{
|
||||
@inlinable
|
||||
public func index(before index: Index) -> Index {
|
||||
Index(inner.index(before: index.inner))
|
||||
}
|
||||
}
|
||||
|
||||
extension JoinedByClosureCollection: LazyCollectionProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Sequence.joined(by:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Sequence where Element: Sequence {
|
||||
/// Returns the concatenation of the elements in this sequence of sequences,
|
||||
/// inserting the given separator between each sequence.
|
||||
///
|
||||
/// for x in [[1, 2], [3, 4], [5, 6]].joined(by: 100) {
|
||||
/// print(x)
|
||||
/// }
|
||||
/// // 1, 2, 100, 3, 4, 100, 5, 6
|
||||
@inlinable
|
||||
public func joined(by separator: Element.Element)
|
||||
-> JoinedBySequence<Self, CollectionOfOne<Element.Element>>
|
||||
{
|
||||
joined(by: CollectionOfOne(separator))
|
||||
}
|
||||
|
||||
/// Returns the concatenation of the elements in this sequence of sequences,
|
||||
/// inserting the given separator between each sequence.
|
||||
///
|
||||
/// for x in [[1, 2], [3, 4], [5, 6]].joined(by: [100, 200]) {
|
||||
/// print(x)
|
||||
/// }
|
||||
/// // 1, 2, 100, 200, 3, 4, 100, 200, 5, 6
|
||||
@inlinable
|
||||
public func joined<Separator>(
|
||||
by separator: Separator
|
||||
) -> JoinedBySequence<Self, Separator>
|
||||
where Separator: Collection, Separator.Element == Element.Element
|
||||
{
|
||||
JoinedBySequence(base: self, separator: separator)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _joined(
|
||||
by update: (inout [Element.Element], Element, Element) throws -> Void
|
||||
) rethrows -> [Element.Element] {
|
||||
var iterator = makeIterator()
|
||||
guard let first = iterator.next() else { return [] }
|
||||
|
||||
var result = Array(first)
|
||||
var previous = first
|
||||
|
||||
while let next = iterator.next() {
|
||||
try update(&result, previous, next)
|
||||
result.append(contentsOf: next)
|
||||
previous = next
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/// Returns the concatenation of the elements in this sequence of sequences,
|
||||
/// inserting the separator produced by the closure between each sequence.
|
||||
///
|
||||
/// for x in [[1, 2], [3, 4], [5, 6]].joined(by: { $0.last! * $1.first! }) {
|
||||
/// print(x)
|
||||
/// }
|
||||
/// // 1, 2, 6, 3, 4, 20, 5, 6
|
||||
@inlinable
|
||||
public func joined(
|
||||
by separator: (Element, Element) throws -> Element.Element
|
||||
) rethrows -> [Element.Element] {
|
||||
try _joined(by: { $0.append(try separator($1, $2)) })
|
||||
}
|
||||
|
||||
/// Returns the concatenation of the elements in this sequence of sequences,
|
||||
/// inserting the separator produced by the closure between each sequence.
|
||||
///
|
||||
/// for x in [[1, 2], [3, 4], [5, 6]].joined(by: { [100 * $0.last!, 100 * $1.first!] }) {
|
||||
/// print(x)
|
||||
/// }
|
||||
/// // 1, 2, 200, 300, 3, 4, 400, 500, 5, 6
|
||||
@inlinable
|
||||
public func joined<Separator>(
|
||||
by separator: (Element, Element) throws -> Separator
|
||||
) rethrows -> [Element.Element]
|
||||
where Separator: Sequence, Separator.Element == Element.Element
|
||||
{
|
||||
try _joined(by: { $0.append(contentsOf: try separator($1, $2)) })
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// LazySequenceProtocol.joined(by:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension LazySequenceProtocol where Element: Sequence {
|
||||
/// Returns the concatenation of the elements in this sequence of sequences,
|
||||
/// inserting the separator produced by the closure between each sequence.
|
||||
@inlinable
|
||||
public func joined(
|
||||
by separator: @escaping (Element, Element) -> Element.Element
|
||||
) -> JoinedByClosureSequence<Elements, CollectionOfOne<Element.Element>> {
|
||||
joined(by: { CollectionOfOne(separator($0, $1)) })
|
||||
}
|
||||
|
||||
/// Returns the concatenation of the elements in this sequence of sequences,
|
||||
/// inserting the separator produced by the closure between each sequence.
|
||||
@inlinable
|
||||
public func joined<Separator>(
|
||||
by separator: @escaping (Element, Element) -> Separator
|
||||
) -> JoinedByClosureSequence<Elements, Separator> {
|
||||
JoinedByClosureSequence(base: elements, separator: separator)
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Collection.joined(by:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Collection where Element: Collection {
|
||||
/// Returns the concatenation of the elements in this collection of
|
||||
/// collections, inserting the given separator between each collection.
|
||||
///
|
||||
/// for x in [[1, 2], [3, 4], [5, 6]].joined(by: 100) {
|
||||
/// print(x)
|
||||
/// }
|
||||
/// // 1, 2, 100, 3, 4, 100, 5, 6
|
||||
@inlinable
|
||||
public func joined(by separator: Element.Element)
|
||||
-> JoinedByCollection<Self, CollectionOfOne<Element.Element>>
|
||||
{
|
||||
joined(by: CollectionOfOne(separator))
|
||||
}
|
||||
|
||||
/// Returns the concatenation of the elements in this collection of
|
||||
/// collections, inserting the given separator between each collection.
|
||||
///
|
||||
/// for x in [[1, 2], [3, 4], [5, 6]].joined(by: [100, 200]) {
|
||||
/// print(x)
|
||||
/// }
|
||||
/// // 1, 2, 100, 200, 3, 4, 100, 200, 5, 6
|
||||
@inlinable
|
||||
public func joined<Separator>(by separator: Separator)
|
||||
-> JoinedByCollection<Self, Separator>
|
||||
{
|
||||
JoinedByCollection(base: self, separator: separator)
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// LazySequenceProtocol.joined(by:) where Self: Collection
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension LazySequenceProtocol where Elements: Collection, Element: Collection {
|
||||
/// Returns the concatenation of the elements in this collection of
|
||||
/// collections, inserting the separator produced by the closure between each
|
||||
/// sequence.
|
||||
@inlinable
|
||||
public func joined(
|
||||
by separator: @escaping (Element, Element) -> Element.Element
|
||||
) -> JoinedByClosureCollection<Elements, CollectionOfOne<Element.Element>> {
|
||||
joined(by: { CollectionOfOne(separator($0, $1)) })
|
||||
}
|
||||
|
||||
/// Returns the concatenation of the elements in this collection of
|
||||
/// collections, inserting the separator produced by the closure between each
|
||||
/// sequence.
|
||||
@inlinable
|
||||
public func joined<Separator>(
|
||||
by separator: @escaping (Element, Element) -> Separator
|
||||
) -> JoinedByClosureCollection<Elements, Separator> {
|
||||
JoinedByClosureCollection(base: elements, separator: separator)
|
||||
}
|
||||
}
|
||||
+107
-10
@@ -28,11 +28,9 @@ extension Sequence {
|
||||
while let e = iterator.next() {
|
||||
// To be part of `result`, `e` must be strictly less than `result.last`.
|
||||
guard try areInIncreasingOrder(e, result.last!) else { continue }
|
||||
result.removeLast()
|
||||
let insertionIndex =
|
||||
try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
|
||||
|
||||
assert(insertionIndex != result.endIndex)
|
||||
result.removeLast()
|
||||
result.insert(e, at: insertionIndex)
|
||||
}
|
||||
|
||||
@@ -127,7 +125,7 @@ extension Sequence {
|
||||
/// largest values:
|
||||
///
|
||||
/// let numbers = [7, 1, 6, 2, 8, 3, 9]
|
||||
/// let smallestThree = numbers.max(count: 3, sortedBy: <)
|
||||
/// let largestThree = numbers.max(count: 3, sortedBy: <)
|
||||
/// // [7, 8, 9]
|
||||
///
|
||||
/// If you need to sort a sequence but only need to access its largest
|
||||
@@ -190,7 +188,7 @@ extension Sequence where Element: Comparable {
|
||||
/// sequence and *k* is `count`.
|
||||
@inlinable
|
||||
public func min(count: Int) -> [Element] {
|
||||
return min(count: count, sortedBy: <)
|
||||
min(count: count, sortedBy: <)
|
||||
}
|
||||
|
||||
/// Returns the largest elements of this sequence.
|
||||
@@ -199,7 +197,7 @@ extension Sequence where Element: Comparable {
|
||||
/// largest values:
|
||||
///
|
||||
/// let numbers = [7, 1, 6, 2, 8, 3, 9]
|
||||
/// let smallestThree = numbers.max(count: 3)
|
||||
/// let largestThree = numbers.max(count: 3)
|
||||
/// // [7, 8, 9]
|
||||
///
|
||||
/// If you need to sort a sequence but only need to access its largest
|
||||
@@ -216,7 +214,7 @@ extension Sequence where Element: Comparable {
|
||||
/// sequence and *k* is `count`.
|
||||
@inlinable
|
||||
public func max(count: Int) -> [Element] {
|
||||
return max(count: count, sortedBy: <)
|
||||
max(count: count, sortedBy: <)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,7 +280,7 @@ extension Collection {
|
||||
/// largest values:
|
||||
///
|
||||
/// let numbers = [7, 1, 6, 2, 8, 3, 9]
|
||||
/// let smallestThree = numbers.max(count: 3, sortedBy: <)
|
||||
/// let largestThree = numbers.max(count: 3, sortedBy: <)
|
||||
/// // [7, 8, 9]
|
||||
///
|
||||
/// If you need to sort a collection but only need to access its largest
|
||||
@@ -354,7 +352,7 @@ extension Collection where Element: Comparable {
|
||||
/// collection and *k* is `count`.
|
||||
@inlinable
|
||||
public func min(count: Int) -> [Element] {
|
||||
return min(count: count, sortedBy: <)
|
||||
min(count: count, sortedBy: <)
|
||||
}
|
||||
|
||||
/// Returns the largest elements of this collection.
|
||||
@@ -380,6 +378,105 @@ extension Collection where Element: Comparable {
|
||||
/// collection and *k* is `count`.
|
||||
@inlinable
|
||||
public func max(count: Int) -> [Element] {
|
||||
return max(count: count, sortedBy: <)
|
||||
max(count: count, sortedBy: <)
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Simultaneous minimum and maximum evaluation
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Sequence {
|
||||
/// Returns both the minimum and maximum elements in the sequence, using the
|
||||
/// given predicate as the comparison between elements.
|
||||
///
|
||||
/// The predicate must be a *strict weak ordering* over the elements. That is,
|
||||
/// for any elements `a`, `b`, and `c`, the following conditions must hold:
|
||||
///
|
||||
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
|
||||
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
|
||||
/// both `true`, then `areInIncreasingOrder(a, c)` is also
|
||||
/// `true`. (Transitive comparability)
|
||||
/// - Two elements are *incomparable* if neither is ordered before the other
|
||||
/// according to the predicate. If `a` and `b` are incomparable, and `b`
|
||||
/// and `c` are incomparable, then `a` and `c` are also incomparable.
|
||||
/// (Transitive incomparability)
|
||||
///
|
||||
/// This example shows how to use the `minAndMax(by:)` method on a dictionary
|
||||
/// to find the key-value pair with the lowest value and the pair with the
|
||||
/// highest value.
|
||||
///
|
||||
/// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
|
||||
/// if let extremeHues = hues.minAndMax(by: {$0.value < $1.value}) {
|
||||
/// print(extremeHues.min, extremeHues.max)
|
||||
/// } else {
|
||||
/// print("There are no hues")
|
||||
/// }
|
||||
/// // Prints: "(key: "Coral", value: 16) (key: "Heliotrope", value: 296)"
|
||||
///
|
||||
/// - Precondition: The sequence is finite.
|
||||
///
|
||||
/// - Parameter areInIncreasingOrder: A predicate that returns `true` if its
|
||||
/// first argument should be ordered before its second argument; otherwise,
|
||||
/// `false`.
|
||||
/// - Returns: A tuple with the sequence's minimum element, followed by its
|
||||
/// maximum element. If the sequence provides multiple qualifying minimum
|
||||
/// elements, the first equivalent element is returned; of multiple maximum
|
||||
/// elements, the last is returned. If the sequence has no elements, the
|
||||
/// method returns `nil`.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
||||
@inlinable
|
||||
public func minAndMax(
|
||||
by areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows -> (min: Element, max: Element)? {
|
||||
// Check short sequences.
|
||||
var iterator = makeIterator()
|
||||
guard var lowest = iterator.next() else { return nil }
|
||||
guard var highest = iterator.next() else { return (lowest, lowest) }
|
||||
|
||||
// Confirm the initial bounds.
|
||||
if try areInIncreasingOrder(highest, lowest) { swap(&lowest, &highest) }
|
||||
|
||||
// Read the elements in pairwise. Structuring the comparisons around this
|
||||
// is actually faster than loops based on extracting and testing elements
|
||||
// one-at-a-time.
|
||||
while var low = iterator.next() {
|
||||
var high = iterator.next() ?? low
|
||||
if try areInIncreasingOrder(high, low) { swap(&low, &high) }
|
||||
if try areInIncreasingOrder(low, lowest) { lowest = low }
|
||||
if try !areInIncreasingOrder(high, highest) { highest = high }
|
||||
}
|
||||
|
||||
return (lowest, highest)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence where Element: Comparable {
|
||||
/// Returns both the minimum and maximum elements in the sequence.
|
||||
///
|
||||
/// This example finds the smallest and largest values in an array of height
|
||||
/// measurements.
|
||||
///
|
||||
/// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
|
||||
/// if let (lowestHeight, greatestHeight) = heights.minAndMax() {
|
||||
/// print(lowestHeight, greatestHeight)
|
||||
/// } else {
|
||||
/// print("The list of heights is empty")
|
||||
/// }
|
||||
/// // Prints: "58.5 67.5"
|
||||
///
|
||||
/// - Precondition: The sequence is finite.
|
||||
///
|
||||
/// - Returns: A tuple with the sequence's minimum element, followed by its
|
||||
/// maximum element. If the sequence provides multiple qualifying minimum
|
||||
/// elements, the first equivalent element is returned; of multiple maximum
|
||||
/// elements, the last is returned. If the sequence has no elements, the
|
||||
/// method returns `nil`.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
||||
@inlinable
|
||||
public func minAndMax() -> (min: Element, max: Element)? {
|
||||
minAndMax(by: <)
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -14,9 +14,9 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension MutableCollection {
|
||||
/// Moves all elements satisfying `belongsInSecondPartition` into a suffix
|
||||
/// of the collection, preserving their relative order, and returns the
|
||||
/// start of the resulting suffix.
|
||||
/// Moves all elements satisfying `belongsInSecondPartition` into a suffix of
|
||||
/// the collection, preserving their relative order, and returns the start of
|
||||
/// the resulting suffix.
|
||||
///
|
||||
/// - Complexity: O(*n* log *n*), where *n* is the number of elements.
|
||||
/// - Precondition:
|
||||
@@ -25,7 +25,7 @@ extension MutableCollection {
|
||||
internal mutating func stablePartition(
|
||||
count n: Int,
|
||||
subrange: Range<Index>,
|
||||
by belongsInSecondPartition: (Element) throws-> Bool
|
||||
by belongsInSecondPartition: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
if n == 0 { return subrange.lowerBound }
|
||||
if n == 1 {
|
||||
@@ -138,22 +138,22 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
// * predicate(self[i]) == true, for i in hi ..< endIndex
|
||||
|
||||
Loop: while true {
|
||||
FindLo: repeat {
|
||||
FindLo: do {
|
||||
while lo < hi {
|
||||
if try belongsInSecondPartition(self[lo]) { break FindLo }
|
||||
formIndex(after: &lo)
|
||||
}
|
||||
break Loop
|
||||
} while false
|
||||
}
|
||||
|
||||
FindHi: repeat {
|
||||
FindHi: do {
|
||||
formIndex(before: &hi)
|
||||
while lo < hi {
|
||||
if try !belongsInSecondPartition(self[hi]) { break FindHi }
|
||||
formIndex(before: &hi)
|
||||
}
|
||||
break Loop
|
||||
} while false
|
||||
}
|
||||
|
||||
swapAt(lo, hi)
|
||||
formIndex(after: &lo)
|
||||
@@ -168,18 +168,19 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Collection {
|
||||
/// Returns the index of the first element in the collection that matches
|
||||
/// the predicate.
|
||||
/// Returns the start index of the partition of a collection that matches
|
||||
/// the given predicate.
|
||||
///
|
||||
/// The collection must already be partitioned according to the predicate.
|
||||
/// That is, there should be an index `i` where for every element in
|
||||
/// `collection[..<i]` the predicate is `false`, and for every element
|
||||
/// in `collection[i...]` the predicate is `true`.
|
||||
/// `collection[..<i]` the predicate is `false`, and for every element in
|
||||
/// `collection[i...]` the predicate is `true`.
|
||||
///
|
||||
/// - Parameter belongsInSecondPartition: A predicate that partitions the
|
||||
/// collection.
|
||||
/// - Returns: The index of the first element in the collection for which
|
||||
/// `predicate` returns `true`.
|
||||
/// `predicate` returns `true`, or `endIndex` if there are no elements
|
||||
/// for which `predicate` returns `true`.
|
||||
///
|
||||
/// - Complexity: O(log *n*), where *n* is the length of this collection if
|
||||
/// the collection conforms to `RandomAccessCollection`, otherwise O(*n*).
|
||||
@@ -204,3 +205,137 @@ extension Collection {
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// partitioned(by:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Sequence {
|
||||
/// Returns two arrays containing, in order, the elements of the sequence that
|
||||
/// do and don’t satisfy the given predicate.
|
||||
///
|
||||
/// In this example, `partitioned(by:)` is used to separate the input based on
|
||||
/// whether a name is shorter than five characters:
|
||||
///
|
||||
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
|
||||
/// let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })
|
||||
/// print(longNames)
|
||||
/// // Prints "["Vivien", "Marlon"]"
|
||||
/// print(shortNames)
|
||||
/// // Prints "["Kim", "Karl"]"
|
||||
///
|
||||
/// - Parameter predicate: A closure that takes an element of the sequence as
|
||||
/// its argument and returns a Boolean value indicating whether the element
|
||||
/// should be included in the second returned array. Otherwise, the element
|
||||
/// will appear in the first returned array.
|
||||
///
|
||||
/// - Returns: Two arrays with all of the elements of the receiver. The
|
||||
/// first array contains all the elements that `predicate` didn’t allow, and
|
||||
/// the second array contains all the elements that `predicate` allowed.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
||||
@inlinable
|
||||
public func partitioned(
|
||||
by predicate: (Element) throws -> Bool
|
||||
) rethrows -> (falseElements: [Element], trueElements: [Element]) {
|
||||
var lhs = [Element]()
|
||||
var rhs = [Element]()
|
||||
|
||||
for element in self {
|
||||
if try predicate(element) {
|
||||
rhs.append(element)
|
||||
} else {
|
||||
lhs.append(element)
|
||||
}
|
||||
}
|
||||
|
||||
return (lhs, rhs)
|
||||
}
|
||||
}
|
||||
|
||||
extension Collection {
|
||||
/// Returns two arrays containing, in order, the elements of the collection
|
||||
/// that do and don’t satisfy the given predicate.
|
||||
///
|
||||
/// In this example, `partitioned(by:)` is used to separate the input based on
|
||||
/// whether a name is shorter than five characters.
|
||||
///
|
||||
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
|
||||
/// let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })
|
||||
/// print(longNames)
|
||||
/// // Prints "["Vivien", "Marlon"]"
|
||||
/// print(shortNames)
|
||||
/// // Prints "["Kim", "Karl"]"
|
||||
///
|
||||
/// - Parameter predicate: A closure that takes an element of the collection
|
||||
/// as its argument and returns a Boolean value indicating whether the element
|
||||
/// should be included in the second returned array. Otherwise, the element
|
||||
/// will appear in the first returned array.
|
||||
///
|
||||
/// - Returns: Two arrays with all of the elements of the receiver. The
|
||||
/// first array contains all the elements that `predicate` didn’t allow, and
|
||||
/// the second array contains all the elements that `predicate` allowed.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
public func partitioned(
|
||||
by predicate: (Element) throws -> Bool
|
||||
) rethrows -> (falseElements: [Element], trueElements: [Element]) {
|
||||
guard !self.isEmpty else {
|
||||
return ([], [])
|
||||
}
|
||||
|
||||
// Since collections have known sizes, we can allocate one array of size
|
||||
// `self.count`, then insert items at the beginning or end of that contiguous
|
||||
// block. This way, we don’t have to do any dynamic array resizing. Since we
|
||||
// insert the right elements on the right side in reverse order, we need to
|
||||
// reverse them back to the original order at the end.
|
||||
|
||||
let count = self.count
|
||||
|
||||
// Inside of the `initializer` closure, we set what the actual mid-point is.
|
||||
// We will use this to partition the single array into two.
|
||||
var midPoint: Int = 0
|
||||
|
||||
let elements = try [Element](
|
||||
unsafeUninitializedCapacity: count,
|
||||
initializingWith: { buffer, initializedCount in
|
||||
var lhs = buffer.baseAddress!
|
||||
var rhs = lhs + buffer.count
|
||||
do {
|
||||
for element in self {
|
||||
if try predicate(element) {
|
||||
rhs -= 1
|
||||
rhs.initialize(to: element)
|
||||
} else {
|
||||
lhs.initialize(to: element)
|
||||
lhs += 1
|
||||
}
|
||||
}
|
||||
|
||||
precondition(lhs == rhs, """
|
||||
Collection's `count` differed from the number of elements iterated.
|
||||
"""
|
||||
)
|
||||
|
||||
let rhsIndex = rhs - buffer.baseAddress!
|
||||
buffer[rhsIndex...].reverse()
|
||||
initializedCount = buffer.count
|
||||
|
||||
midPoint = rhsIndex
|
||||
} catch {
|
||||
let lhsCount = lhs - buffer.baseAddress!
|
||||
let rhsCount = (buffer.baseAddress! + buffer.count) - rhs
|
||||
buffer.baseAddress!.deinitialize(count: lhsCount)
|
||||
rhs.deinitialize(count: rhsCount)
|
||||
throw error
|
||||
}
|
||||
})
|
||||
|
||||
let lhs = elements[..<midPoint]
|
||||
let rhs = elements[midPoint...]
|
||||
return (
|
||||
Array(lhs),
|
||||
Array(rhs)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -18,9 +18,9 @@ extension MutableCollection
|
||||
{
|
||||
/// Permutes this collection's elements through all the lexical orderings.
|
||||
///
|
||||
/// Call `nextPermutation()` repeatedly starting with the collection in
|
||||
/// sorted order. When the full cycle of all permutations has been completed,
|
||||
/// the collection will be back in sorted order and this method will return
|
||||
/// Call `nextPermutation()` repeatedly starting with the collection in sorted
|
||||
/// order. When the full cycle of all permutations has been completed, the
|
||||
/// collection will be back in sorted order and this method will return
|
||||
/// `false`.
|
||||
///
|
||||
/// - Returns: A Boolean value indicating whether the collection still has
|
||||
@@ -76,20 +76,24 @@ extension MutableCollection
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A sequence of all the permutations of a collection's elements.
|
||||
public struct Permutations<Base: Collection> {
|
||||
public struct PermutationsSequence<Base: Collection> {
|
||||
/// The base collection to iterate over for permutations.
|
||||
public let base: Base
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let baseCount: Int
|
||||
|
||||
/// The range of accepted sizes of permutations.
|
||||
///
|
||||
/// - Note: This may be empty if the attempted range entirely exceeds the
|
||||
/// bounds of the size of the `base` collection.
|
||||
@usableFromInline
|
||||
internal let kRange: Range<Int>
|
||||
|
||||
/// Initializes a `Permutations` for all permutations of `base` of size `k`.
|
||||
/// Initializes a `PermutationsSequence` for all permutations of `base` of
|
||||
/// size `k`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - base: The collection to iterate over for permutations
|
||||
/// - k: The expected size of each permutation, or `nil` (default) to
|
||||
@@ -105,8 +109,9 @@ public struct Permutations<Base: Collection> {
|
||||
self.init(base, kRange: kRange)
|
||||
}
|
||||
|
||||
/// Initializes a `Permutations` for all combinations of `base` of sizes
|
||||
/// within a given range.
|
||||
/// Initializes a `PermutationsSequence` for all combinations of `base` of
|
||||
/// sizes within a given range.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - base: The collection to iterate over for permutations.
|
||||
/// - kRange: The range of accepted sizes of permutations, or `nil` to
|
||||
@@ -127,17 +132,17 @@ public struct Permutations<Base: Collection> {
|
||||
/// The total number of permutations.
|
||||
@inlinable
|
||||
public var count: Int {
|
||||
return kRange.map {
|
||||
kRange.map {
|
||||
stride(from: baseCount, to: baseCount - $0, by: -1).reduce(1, *)
|
||||
}.reduce(0, +)
|
||||
}
|
||||
}
|
||||
|
||||
extension Permutations: Sequence {
|
||||
/// The iterator for a `Permutations` instance.
|
||||
extension PermutationsSequence: Sequence {
|
||||
/// The iterator for a `PermutationsSequence` instance.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var base: Base
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let baseCount: Int
|
||||
@@ -159,7 +164,7 @@ extension Permutations: Sequence {
|
||||
internal var indexes: [Base.Index]
|
||||
|
||||
@inlinable
|
||||
internal init(_ permutations: Permutations) {
|
||||
internal init(_ permutations: PermutationsSequence) {
|
||||
self.base = permutations.base
|
||||
self.baseCount = permutations.baseCount
|
||||
self.kRange = permutations.kRange
|
||||
@@ -258,7 +263,8 @@ extension Permutations: Sequence {
|
||||
}
|
||||
}
|
||||
|
||||
extension Permutations: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
extension PermutationsSequence: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// permutations(ofCount:)
|
||||
@@ -319,13 +325,13 @@ extension Collection {
|
||||
/// results in an empty sequence.
|
||||
///
|
||||
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
|
||||
/// is the number of elements in the base collection, since `Permutations`
|
||||
/// accesses the `count` of the base collection.
|
||||
/// is the number of elements in the base collection, since
|
||||
/// `PermutationsSequence` accesses the `count` of the base collection.
|
||||
@inlinable
|
||||
public func permutations<R: RangeExpression>(
|
||||
ofCount kRange: R
|
||||
) -> Permutations<Self> where R.Bound == Int {
|
||||
return Permutations(self, kRange: kRange)
|
||||
) -> PermutationsSequence<Self> where R.Bound == Int {
|
||||
PermutationsSequence(self, kRange: kRange)
|
||||
}
|
||||
|
||||
/// Returns a collection of the permutations of this collection of the
|
||||
@@ -375,14 +381,14 @@ extension Collection {
|
||||
/// this collection, the resulting sequence is empty.
|
||||
///
|
||||
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
|
||||
/// is the number of elements in the base collection, since `Permutations`
|
||||
/// accesses the `count` of the base collection.
|
||||
/// is the number of elements in the base collection, since
|
||||
/// `PermutationsSequence` accesses the `count` of the base collection.
|
||||
@inlinable
|
||||
public func permutations(ofCount k: Int? = nil) -> Permutations<Self> {
|
||||
public func permutations(ofCount k: Int? = nil) -> PermutationsSequence<Self> {
|
||||
precondition(
|
||||
k ?? 0 >= 0,
|
||||
"Can't have permutations with a negative number of elements.")
|
||||
return Permutations(self, k: k)
|
||||
return PermutationsSequence(self, k: k)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -393,11 +399,12 @@ extension Collection {
|
||||
/// A sequence of the unique permutations of the elements of a sequence or
|
||||
/// collection.
|
||||
///
|
||||
/// To create a `UniquePermutations` instance, call one of the
|
||||
/// To create a `UniquePermutationsSequence` instance, call one of the
|
||||
/// `uniquePermutations` methods on your collection.
|
||||
public struct UniquePermutations<Base: Collection> {
|
||||
public struct UniquePermutationsSequence<Base: Collection> {
|
||||
/// The base collection to iterate over for permutations.
|
||||
public let base: Base
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal var indexes: [Base.Index]
|
||||
@@ -406,7 +413,7 @@ public struct UniquePermutations<Base: Collection> {
|
||||
internal let kRange: Range<Int>
|
||||
}
|
||||
|
||||
extension UniquePermutations where Base.Element: Hashable {
|
||||
extension UniquePermutationsSequence where Base.Element: Hashable {
|
||||
@inlinable
|
||||
internal static func _indexes(_ base: Base) -> [Base.Index] {
|
||||
let firstIndexesAndCountsByElement = Dictionary(
|
||||
@@ -438,8 +445,8 @@ extension UniquePermutations where Base.Element: Hashable {
|
||||
}
|
||||
}
|
||||
|
||||
extension UniquePermutations: Sequence {
|
||||
/// The iterator for a `UniquePermutations` instance.
|
||||
extension UniquePermutationsSequence: Sequence {
|
||||
/// The iterator for a `UniquePermutationsSequence` instance.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
@@ -494,7 +501,8 @@ extension UniquePermutations: Sequence {
|
||||
}
|
||||
}
|
||||
|
||||
extension UniquePermutations: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
extension UniquePermutationsSequence: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
extension Collection where Element: Hashable {
|
||||
/// Returns a sequence of the unique permutations of this sequence of the
|
||||
@@ -535,11 +543,14 @@ extension Collection where Element: Hashable {
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the number of elements in this
|
||||
/// collection.
|
||||
public func uniquePermutations(ofCount k: Int? = nil) -> UniquePermutations<Self> {
|
||||
@inlinable
|
||||
public func uniquePermutations(ofCount k: Int? = nil)
|
||||
-> UniquePermutationsSequence<Self>
|
||||
{
|
||||
if let k = k {
|
||||
return UniquePermutations(self, k ..< (k + 1))
|
||||
return UniquePermutationsSequence(self, k ..< (k + 1))
|
||||
} else {
|
||||
return UniquePermutations(self)
|
||||
return UniquePermutationsSequence(self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -572,9 +583,10 @@ extension Collection where Element: Hashable {
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the number of elements in this
|
||||
/// collection.
|
||||
public func uniquePermutations<R: RangeExpression>(ofCount kRange: R) -> UniquePermutations<Self>
|
||||
where R.Bound == Int
|
||||
{
|
||||
UniquePermutations(self, kRange)
|
||||
@inlinable
|
||||
public func uniquePermutations<R: RangeExpression>(
|
||||
ofCount kRange: R
|
||||
) -> UniquePermutationsSequence<Self> where R.Bound == Int {
|
||||
UniquePermutationsSequence(self, kRange)
|
||||
}
|
||||
}
|
||||
@@ -10,11 +10,14 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A sequence that represents the product of two sequences' elements.
|
||||
public struct Product2<Base1: Sequence, Base2: Collection> {
|
||||
public struct Product2Sequence<Base1: Sequence, Base2: Collection> {
|
||||
/// The outer sequence in the product.
|
||||
public let base1: Base1
|
||||
@usableFromInline
|
||||
internal let base1: Base1
|
||||
|
||||
/// The inner sequence in the product.
|
||||
public let base2: Base2
|
||||
@usableFromInline
|
||||
internal let base2: Base2
|
||||
|
||||
@inlinable
|
||||
internal init(_ base1: Base1, _ base2: Base2) {
|
||||
@@ -23,8 +26,10 @@ public struct Product2<Base1: Sequence, Base2: Collection> {
|
||||
}
|
||||
}
|
||||
|
||||
extension Product2: Sequence {
|
||||
/// The iterator for a `Product2` sequence.
|
||||
extension Product2Sequence: Sequence {
|
||||
public typealias Element = (Base1.Element, Base2.Element)
|
||||
|
||||
/// The iterator for a `Product2Sequence` sequence.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var i1: Base1.Iterator
|
||||
@@ -36,7 +41,7 @@ extension Product2: Sequence {
|
||||
internal let base2: Base2
|
||||
|
||||
@inlinable
|
||||
internal init(_ c: Product2) {
|
||||
internal init(_ c: Product2Sequence) {
|
||||
self.base2 = c.base2
|
||||
self.i1 = c.base1.makeIterator()
|
||||
self.i2 = c.base2.makeIterator()
|
||||
@@ -44,7 +49,8 @@ extension Product2: Sequence {
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> (Base1.Element, Base2.Element)? {
|
||||
public mutating func next() -> (Base1.Element,
|
||||
Base2.Element)? {
|
||||
// This is the initial state, where i1.next() has never
|
||||
// been called, or the final state, where i1.next() has
|
||||
// already returned nil.
|
||||
@@ -77,13 +83,14 @@ extension Product2: Sequence {
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
return Iterator(self)
|
||||
Iterator(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension Product2: Collection where Base1: Collection {
|
||||
/// The index type for a `Product2` collection.
|
||||
extension Product2Sequence: Collection where Base1: Collection {
|
||||
/// The index type for a `Product2Sequence` collection.
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal var i1: Base1.Index
|
||||
@@ -121,7 +128,8 @@ extension Product2: Collection where Base1: Collection {
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> (Base1.Element, Base2.Element) {
|
||||
public subscript(position: Index) -> (Base1.Element,
|
||||
Base2.Element) {
|
||||
(base1[position.i1], base2[position.i2])
|
||||
}
|
||||
|
||||
@@ -412,7 +420,7 @@ extension Product2: Collection where Base1: Collection {
|
||||
}
|
||||
}
|
||||
|
||||
extension Product2: BidirectionalCollection
|
||||
extension Product2Sequence: BidirectionalCollection
|
||||
where Base1: BidirectionalCollection, Base2: BidirectionalCollection
|
||||
{
|
||||
@inlinable
|
||||
@@ -429,12 +437,11 @@ extension Product2: BidirectionalCollection
|
||||
}
|
||||
}
|
||||
|
||||
extension Product2: RandomAccessCollection
|
||||
extension Product2Sequence: RandomAccessCollection
|
||||
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
|
||||
|
||||
extension Product2.Index: Hashable where Base1.Index: Hashable, Base2.Index: Hashable {}
|
||||
extension Product2: Equatable where Base1: Equatable, Base2: Equatable {}
|
||||
extension Product2: Hashable where Base1: Hashable, Base2: Hashable {}
|
||||
extension Product2Sequence.Index: Hashable
|
||||
where Base1.Index: Hashable, Base2.Index: Hashable {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// product(_:_:)
|
||||
@@ -476,6 +483,6 @@ extension Product2: Hashable where Base1: Hashable, Base2: Hashable {}
|
||||
@inlinable
|
||||
public func product<Base1: Sequence, Base2: Collection>(
|
||||
_ s1: Base1, _ s2: Base2
|
||||
) -> Product2<Base1, Base2> {
|
||||
return Product2(s1, s2)
|
||||
) -> Product2Sequence<Base1, Base2> {
|
||||
Product2Sequence(s1, s2)
|
||||
}
|
||||
@@ -62,8 +62,7 @@ extension Collection {
|
||||
/// This method is equivalent to calling `randomStableSample(k:using:)`,
|
||||
/// passing in the system's default random generator.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - k: The number of elements to randomly select.
|
||||
/// - Parameter k: The number of elements to randomly select.
|
||||
/// - Returns: An array of `k` random elements. If `k` is greater than this
|
||||
/// collection's count, then this method returns the full collection.
|
||||
///
|
||||
@@ -123,12 +122,12 @@ extension Collection {
|
||||
|
||||
// Fill the reservoir with the first `k` elements.
|
||||
var i = startIndex
|
||||
while i < endIndex, result.count < k {
|
||||
while i != endIndex, result.count < k {
|
||||
result.append(self[i])
|
||||
formIndex(after: &i)
|
||||
}
|
||||
|
||||
while i < endIndex {
|
||||
while i != endIndex {
|
||||
// Calculate the next value of w.
|
||||
w *= nextW(k: k, using: &rng)
|
||||
|
||||
@@ -136,7 +135,7 @@ extension Collection {
|
||||
let offset = nextOffset(w: w, using: &rng)
|
||||
i = index(i, offsetBy: offset, limitedBy: endIndex) ?? endIndex
|
||||
|
||||
if i < endIndex {
|
||||
if i != endIndex {
|
||||
// Swap selected element with a randomly chosen one in the reservoir.
|
||||
let j = Int.random(in: 0..<result.count, using: &rng)
|
||||
result[j] = self[i]
|
||||
@@ -154,8 +153,7 @@ extension Collection {
|
||||
/// This method is equivalent to calling `randomSample(k:using:)`, passing in
|
||||
/// the system's default random generator.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - k: The number of elements to randomly select.
|
||||
/// - Parameter k: The number of elements to randomly select.
|
||||
/// - Returns: An array of `k` random elements. The returned elements may be
|
||||
/// in any order. If `k` is greater than this collection's count, then this
|
||||
/// method returns the full collection.
|
||||
@@ -225,8 +223,7 @@ extension Sequence {
|
||||
/// This method is equivalent to calling `randomSample(k:using:)`, passing in
|
||||
/// the system's default random generator.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - k: The number of elements to randomly select.
|
||||
/// - Parameter k: The number of elements to randomly select.
|
||||
/// - Returns: An array of `k` random elements. The returned elements may be
|
||||
/// in any order. If `k` is greater than this sequence's count, then this
|
||||
/// method returns the full sequence.
|
||||
|
||||
+141
-164
@@ -12,7 +12,6 @@
|
||||
// MARK: - Exclusive Reductions
|
||||
|
||||
extension LazySequenceProtocol {
|
||||
|
||||
/// Returns a sequence containing the accumulated results of combining the
|
||||
/// elements of the sequence using the given closure.
|
||||
///
|
||||
@@ -29,17 +28,17 @@ extension LazySequenceProtocol {
|
||||
/// - Parameters:
|
||||
/// - initial: The value to use as the initial value.
|
||||
/// - transform: A closure that combines the previously reduced result and
|
||||
/// the next element in the receiving sequence.
|
||||
/// the next element in the receiving sequence.
|
||||
/// - Returns: A sequence of the initial value followed by the reduced
|
||||
/// elements.
|
||||
/// elements.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func reductions<Result>(
|
||||
_ initial: Result,
|
||||
_ transform: @escaping (Result, Element) -> Result
|
||||
) -> ExclusiveReductions<Result, Self> {
|
||||
return reductions(into: initial) { result, element in
|
||||
) -> ExclusiveReductionsSequence<Elements, Result> {
|
||||
reductions(into: initial) { result, element in
|
||||
result = transform(result, element)
|
||||
}
|
||||
}
|
||||
@@ -60,7 +59,7 @@ extension LazySequenceProtocol {
|
||||
/// - Parameters:
|
||||
/// - initial: The value to use as the initial value.
|
||||
/// - transform: A closure that combines the previously reduced result and
|
||||
/// the next element in the receiving sequence.
|
||||
/// the next element in the receiving sequence.
|
||||
/// - Returns: A sequence of the initial value followed by the reduced
|
||||
/// elements.
|
||||
///
|
||||
@@ -69,13 +68,15 @@ extension LazySequenceProtocol {
|
||||
public func reductions<Result>(
|
||||
into initial: Result,
|
||||
_ transform: @escaping (inout Result, Element) -> Void
|
||||
) -> ExclusiveReductions<Result, Self> {
|
||||
ExclusiveReductions(base: self, initial: initial, transform: transform)
|
||||
) -> ExclusiveReductionsSequence<Elements, Result> {
|
||||
ExclusiveReductionsSequence(
|
||||
base: elements,
|
||||
initial: initial,
|
||||
transform: transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
|
||||
/// Returns an array containing the accumulated results of combining the
|
||||
/// elements of the sequence using the given closure.
|
||||
///
|
||||
@@ -106,7 +107,7 @@ extension Sequence {
|
||||
/// - Parameters:
|
||||
/// - initial: The value to use as the initial value.
|
||||
/// - transform: A closure that combines the previously reduced result and
|
||||
/// the next element in the receiving sequence.
|
||||
/// the next element in the receiving sequence.
|
||||
/// - Returns: An array of the initial value followed by the reduced elements.
|
||||
///
|
||||
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
|
||||
@@ -115,7 +116,7 @@ extension Sequence {
|
||||
_ initial: Result,
|
||||
_ transform: (Result, Element) throws -> Result
|
||||
) rethrows -> [Result] {
|
||||
return try reductions(into: initial) { result, element in
|
||||
try reductions(into: initial) { result, element in
|
||||
result = try transform(result, element)
|
||||
}
|
||||
}
|
||||
@@ -150,7 +151,7 @@ extension Sequence {
|
||||
/// - Parameters:
|
||||
/// - initial: The value to use as the initial value.
|
||||
/// - transform: A closure that combines the previously reduced result and
|
||||
/// the next element in the receiving sequence.
|
||||
/// the next element in the receiving sequence.
|
||||
/// - Returns: An array of the initial value followed by the reduced elements.
|
||||
///
|
||||
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
|
||||
@@ -176,7 +177,7 @@ extension Sequence {
|
||||
|
||||
/// A sequence of applying a transform to the element of a sequence and the
|
||||
/// previously transformed result.
|
||||
public struct ExclusiveReductions<Result, Base: Sequence> {
|
||||
public struct ExclusiveReductionsSequence<Base: Sequence, Result> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@@ -198,7 +199,7 @@ public struct ExclusiveReductions<Result, Base: Sequence> {
|
||||
}
|
||||
}
|
||||
|
||||
extension ExclusiveReductions: Sequence {
|
||||
extension ExclusiveReductionsSequence: Sequence {
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var iterator: Base.Iterator
|
||||
@@ -234,58 +235,82 @@ extension ExclusiveReductions: Sequence {
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(iterator: base.makeIterator(),
|
||||
current: initial,
|
||||
transform: transform)
|
||||
Iterator(
|
||||
iterator: base.makeIterator(),
|
||||
current: initial,
|
||||
transform: transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension ExclusiveReductions: Collection where Base: Collection {
|
||||
extension ExclusiveReductionsSequence: Collection where Base: Collection {
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal let representation: ReductionsIndexRepresentation<Base.Index, Result>
|
||||
internal enum Representation {
|
||||
case base(Base.Index, Result)
|
||||
case end
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal let representation: Representation
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
_ representation: ReductionsIndexRepresentation<Base.Index, Result>
|
||||
) {
|
||||
internal init(_ representation: Representation) {
|
||||
self.representation = representation
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
switch (lhs.representation, rhs.representation) {
|
||||
case (.base(let lhs, _), .base(let rhs, _)):
|
||||
return lhs == rhs
|
||||
case (.end, .end):
|
||||
return true
|
||||
case (.base, .end), (.end, .base):
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.representation < rhs.representation
|
||||
switch (lhs.representation, rhs.representation) {
|
||||
case (.end, _):
|
||||
return false
|
||||
case (_, .end):
|
||||
return true
|
||||
case (.base(let lhs, _), .base(let rhs, _)):
|
||||
return lhs < rhs
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index { Index(.start) }
|
||||
public var startIndex: Index {
|
||||
Index(.base(base.startIndex, initial))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index { Index(.end) }
|
||||
public var endIndex: Index {
|
||||
Index(.end)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> Result {
|
||||
switch position.representation {
|
||||
case .start: return initial
|
||||
case .base(_, let result): return result
|
||||
case .end: fatalError("Cannot get element of end index.")
|
||||
case .base(_, let result):
|
||||
return result
|
||||
case .end:
|
||||
fatalError("Cannot get element of end index.")
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
func index(base index: Base.Index, previous: Result) -> Index {
|
||||
guard index != base.endIndex else { return endIndex }
|
||||
var previous = previous
|
||||
transform(&previous, base[index])
|
||||
return Index(.base(index: index, result: previous))
|
||||
}
|
||||
switch i.representation {
|
||||
case .start:
|
||||
return index(base: base.startIndex, previous: initial)
|
||||
case let .base(i, result):
|
||||
return index(base: base.index(after: i), previous: result)
|
||||
public func index(after index: Index) -> Index {
|
||||
switch index.representation {
|
||||
case .base(base.endIndex, _):
|
||||
return Index(.end)
|
||||
case .base(let index, var result):
|
||||
transform(&result, base[index])
|
||||
return Index(.base(base.index(after: index), result))
|
||||
case .end:
|
||||
fatalError("Cannot get index after end index.")
|
||||
}
|
||||
@@ -294,38 +319,40 @@ extension ExclusiveReductions: Collection where Base: Collection {
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
switch (start.representation, end.representation) {
|
||||
case (.start, .start):
|
||||
return 0
|
||||
case let (.start, .base(index, _)):
|
||||
return base.distance(from: base.startIndex, to: index) + 1
|
||||
case (.start, .end):
|
||||
return base.distance(from: base.startIndex, to: base.endIndex) + 1
|
||||
case let (.base(index, _), .start):
|
||||
return base.distance(from: index, to: base.startIndex) - 1
|
||||
case let (.base(start, _), .base(end, _)):
|
||||
return base.distance(from: start, to: end)
|
||||
case let (.base(index, _), .end):
|
||||
return base.distance(from: index, to: base.endIndex)
|
||||
case (.end, .start):
|
||||
return base.distance(from: base.endIndex, to: base.startIndex) - 1
|
||||
return base.distance(from: index, to: base.endIndex) + 1
|
||||
case let (.end, .base(index, _)):
|
||||
return base.distance(from: base.endIndex, to: index)
|
||||
return base.distance(from: base.endIndex, to: index) - 1
|
||||
case (.end, .end):
|
||||
return 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension ExclusiveReductions: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
extension ExclusiveReductionsSequence: LazySequenceProtocol {}
|
||||
|
||||
extension ExclusiveReductions: LazyCollectionProtocol
|
||||
where Base: LazyCollectionProtocol {}
|
||||
extension ExclusiveReductionsSequence: LazyCollectionProtocol
|
||||
where Base: Collection {}
|
||||
|
||||
extension ExclusiveReductionsSequence.Index: Hashable
|
||||
where Base.Index: Hashable
|
||||
{
|
||||
@inlinable
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
switch representation {
|
||||
case .base(let base, _):
|
||||
hasher.combine(base)
|
||||
case .end:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Inclusive Reductions
|
||||
|
||||
extension LazySequenceProtocol {
|
||||
|
||||
/// Returns a sequence containing the accumulated results of combining the
|
||||
/// elements of the sequence using the given closure.
|
||||
///
|
||||
@@ -339,22 +366,20 @@ extension LazySequenceProtocol {
|
||||
/// // prints [1, 3, 6, 10]
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - transform: A closure that combines the previously reduced result and
|
||||
/// the next element in the receiving sequence.
|
||||
/// - Parameter transform: A closure that combines the previously reduced
|
||||
/// result and the next element in the receiving sequence.
|
||||
/// - Returns: A sequence of the reduced elements.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func reductions(
|
||||
_ transform: @escaping (Element, Element) -> Element
|
||||
) -> InclusiveReductions<Self> {
|
||||
InclusiveReductions(base: self, transform: transform)
|
||||
) -> InclusiveReductionsSequence<Elements> {
|
||||
InclusiveReductionsSequence(base: elements, transform: transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
|
||||
/// Returns an array containing the accumulated results of combining the
|
||||
/// elements of the sequence using the given closure.
|
||||
///
|
||||
@@ -384,9 +409,8 @@ extension Sequence {
|
||||
/// If the sequence has one element, `transform` is never executed and
|
||||
/// an array containing only that first element is returned.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - transform: A closure that combines the previously reduced result and
|
||||
/// the next element in the receiving sequence.
|
||||
/// - Parameter transform: A closure that combines the previously reduced
|
||||
/// result and the next element in the receiving sequence.
|
||||
/// - Returns: An array of the reduced elements.
|
||||
///
|
||||
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
|
||||
@@ -400,7 +424,7 @@ extension Sequence {
|
||||
}
|
||||
}
|
||||
|
||||
public struct InclusiveReductions<Base: Sequence> {
|
||||
public struct InclusiveReductionsSequence<Base: Sequence> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@@ -417,7 +441,7 @@ public struct InclusiveReductions<Base: Sequence> {
|
||||
}
|
||||
}
|
||||
|
||||
extension InclusiveReductions: Sequence {
|
||||
extension InclusiveReductionsSequence: Sequence {
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var iterator: Base.Iterator
|
||||
@@ -431,11 +455,9 @@ extension InclusiveReductions: Sequence {
|
||||
@inlinable
|
||||
internal init(
|
||||
iterator: Base.Iterator,
|
||||
element: Base.Element? = nil,
|
||||
transform: @escaping (Base.Element, Base.Element) -> Base.Element
|
||||
) {
|
||||
self.iterator = iterator
|
||||
self.element = element
|
||||
self.transform = transform
|
||||
}
|
||||
|
||||
@@ -453,139 +475,97 @@ extension InclusiveReductions: Sequence {
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(iterator: base.makeIterator(),
|
||||
transform: transform)
|
||||
Iterator(iterator: base.makeIterator(), transform: transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension InclusiveReductions: Collection where Base: Collection {
|
||||
extension InclusiveReductionsSequence: Collection where Base: Collection {
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal let representation: ReductionsIndexRepresentation<Base.Index, Base.Element>
|
||||
internal let base: Base.Index
|
||||
|
||||
@usableFromInline
|
||||
internal let result: Element?
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
_ representation: ReductionsIndexRepresentation<Base.Index, Base.Element>
|
||||
) {
|
||||
self.representation = representation
|
||||
internal init(base: Base.Index, result: Element?) {
|
||||
self.base = base
|
||||
self.result = result
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.representation < rhs.representation
|
||||
lhs.base < rhs.base
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.base == rhs.base
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
guard base.startIndex != base.endIndex else { return endIndex }
|
||||
return Index(.start)
|
||||
Index(base: base.startIndex, result: base.first)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index { Index(.end) }
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> Base.Element {
|
||||
switch position.representation {
|
||||
case .start: return base[base.startIndex]
|
||||
case .base(_, let result): return result
|
||||
case .end: fatalError("Cannot get element of end index.")
|
||||
}
|
||||
public var endIndex: Index {
|
||||
Index(base: base.endIndex, result: nil)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
func index(after i: Base.Index, previous: Base.Element) -> Index {
|
||||
let index = base.index(after: i)
|
||||
guard index != base.endIndex else { return endIndex }
|
||||
return Index(.base(index: index, result: transform(previous, base[index])))
|
||||
public subscript(index: Index) -> Base.Element {
|
||||
guard let result = index.result else {
|
||||
fatalError("Can't subscript using endIndex")
|
||||
}
|
||||
switch i.representation {
|
||||
case .start:
|
||||
return index(after: base.startIndex, previous: base[base.startIndex])
|
||||
case let .base(i, element):
|
||||
return index(after: i, previous: element)
|
||||
case .end:
|
||||
fatalError("Cannot get index after end index.")
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after index: Index) -> Index {
|
||||
guard let result = index.result else {
|
||||
fatalError("Can't advance past endIndex")
|
||||
}
|
||||
|
||||
let index = base.index(after: index.base)
|
||||
let nextResult = index == base.endIndex
|
||||
? nil
|
||||
: transform(result, base[index])
|
||||
|
||||
return Index(base: index, result: nextResult)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
switch (start.representation, end.representation) {
|
||||
case (.start, .start):
|
||||
return 0
|
||||
case let (.start, .base(index, _)):
|
||||
return base.distance(from: base.startIndex, to: index)
|
||||
case (.start, .end):
|
||||
return base.distance(from: base.startIndex, to: base.endIndex)
|
||||
case let (.base(index, _), .start):
|
||||
return base.distance(from: index, to: base.startIndex)
|
||||
case let (.base(start, _), .base(end, _)):
|
||||
return base.distance(from: start, to: end)
|
||||
case let (.base(index, _), .end):
|
||||
return base.distance(from: index, to: base.endIndex)
|
||||
case (.end, .start):
|
||||
return base.distance(from: base.endIndex, to: base.startIndex)
|
||||
case let (.end, .base(index, _)):
|
||||
return base.distance(from: base.endIndex, to: index)
|
||||
case (.end, .end):
|
||||
return 0
|
||||
}
|
||||
base.distance(from: start.base, to: end.base)
|
||||
}
|
||||
}
|
||||
|
||||
extension InclusiveReductions: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
extension InclusiveReductionsSequence: LazySequenceProtocol {}
|
||||
|
||||
extension InclusiveReductions: LazyCollectionProtocol
|
||||
where Base: LazyCollectionProtocol {}
|
||||
extension InclusiveReductionsSequence: LazyCollectionProtocol
|
||||
where Base: Collection {}
|
||||
|
||||
// MARK: - ReductionsIndexRepresentation
|
||||
|
||||
@usableFromInline
|
||||
enum ReductionsIndexRepresentation<BaseIndex: Comparable, Result> {
|
||||
case start
|
||||
case base(index: BaseIndex, result: Result)
|
||||
case end
|
||||
}
|
||||
|
||||
extension ReductionsIndexRepresentation: Equatable {
|
||||
extension InclusiveReductionsSequence.Index: Hashable
|
||||
where Base.Index: Hashable
|
||||
{
|
||||
@inlinable
|
||||
static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case (.start, .start): return true
|
||||
case (.end, .end): return true
|
||||
case let (.base(lhs, _), .base(rhs, _)): return lhs == rhs
|
||||
default: return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension ReductionsIndexRepresentation: Comparable {
|
||||
@inlinable
|
||||
static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case (_, .start): return false
|
||||
case (.start, _): return true
|
||||
case (.end, _): return false
|
||||
case (_, .end): return true
|
||||
case let (.base(lhs, _), .base(rhs, _)): return lhs < rhs
|
||||
}
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(base)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Scan
|
||||
|
||||
extension LazySequenceProtocol {
|
||||
|
||||
@available(*, deprecated, message: "Use reductions(_:_:) instead.")
|
||||
@inlinable
|
||||
public func scan<Result>(
|
||||
_ initial: Result,
|
||||
_ transform: @escaping (Result, Element) -> Result
|
||||
) -> ExclusiveReductions<Result, Self> {
|
||||
) -> ExclusiveReductionsSequence<Elements, Result> {
|
||||
reductions(initial, transform)
|
||||
}
|
||||
|
||||
@@ -594,13 +574,12 @@ extension LazySequenceProtocol {
|
||||
public func scan<Result>(
|
||||
into initial: Result,
|
||||
_ transform: @escaping (inout Result, Element) -> Void
|
||||
) -> ExclusiveReductions<Result, Self> {
|
||||
) -> ExclusiveReductionsSequence<Elements, Result> {
|
||||
reductions(into: initial, transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
|
||||
@available(*, deprecated, message: "Use reductions(_:_:) instead.")
|
||||
@inlinable
|
||||
public func scan<Result>(
|
||||
@@ -621,18 +600,16 @@ extension Sequence {
|
||||
}
|
||||
|
||||
extension LazySequenceProtocol {
|
||||
|
||||
@available(*, deprecated, message: "Use reductions(_:) instead.")
|
||||
@inlinable
|
||||
public func scan(
|
||||
_ transform: @escaping (Element, Element) -> Element
|
||||
) -> InclusiveReductions<Self> {
|
||||
) -> InclusiveReductionsSequence<Elements> {
|
||||
reductions(transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
|
||||
@available(*, deprecated, message: "Use reductions(_:) instead.")
|
||||
@inlinable
|
||||
public func scan(
|
||||
|
||||
@@ -75,8 +75,8 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
|
||||
extension MutableCollection {
|
||||
/// Swaps the elements of the two given subranges, up to the upper bound of
|
||||
/// the smaller subrange. The returned indices are the ends of the two
|
||||
/// ranges that were actually swapped.
|
||||
/// the smaller subrange. The returned indices are the ends of the two ranges
|
||||
/// that were actually swapped.
|
||||
///
|
||||
/// Input:
|
||||
/// [a b c d e f g h i j k l m n o p]
|
||||
@@ -112,8 +112,8 @@ extension MutableCollection {
|
||||
return (p, q)
|
||||
}
|
||||
|
||||
/// Rotates the elements within the given subrange so that the element
|
||||
/// at the specified index becomes the start of the subrange.
|
||||
/// Rotates the elements within the given subrange so that the element at the
|
||||
/// specified index becomes the start of the subrange.
|
||||
///
|
||||
/// Rotating a collection is equivalent to breaking the collection into two
|
||||
/// sections at the index `newStart`, and then swapping those two sections.
|
||||
@@ -146,10 +146,9 @@ extension MutableCollection {
|
||||
if s == m { return e }
|
||||
if m == e { return s }
|
||||
|
||||
// We have two regions of possibly-unequal length that need to be
|
||||
// exchanged. The return value of this method is going to be the
|
||||
// position following that of the element that is currently last
|
||||
// (element j).
|
||||
// We have two regions of possibly-unequal length that need to be exchanged.
|
||||
// The return value of this method is going to be the position following
|
||||
// that of the element that is currently last (element j).
|
||||
//
|
||||
// [a b c d e f g|h i j] or [a b c|d e f g h i j]
|
||||
// ^ ^ ^ ^ ^ ^
|
||||
@@ -157,8 +156,8 @@ extension MutableCollection {
|
||||
//
|
||||
var ret = e // start with a known incorrect result.
|
||||
while true {
|
||||
// Exchange the leading elements of each region (up to the
|
||||
// length of the shorter region).
|
||||
// Exchange the leading elements of each region (up to the length of the
|
||||
// shorter region).
|
||||
//
|
||||
// [a b c d e f g|h i j] or [a b c|d e f g h i j]
|
||||
// ^^^^^ ^^^^^ ^^^^^ ^^^^^
|
||||
@@ -169,21 +168,20 @@ extension MutableCollection {
|
||||
let (s1, m1) = _swapNonemptySubrangePrefixes(s..<m, m..<e)
|
||||
|
||||
if m1 == e {
|
||||
// Left-hand case: we have moved element j into position. if
|
||||
// we haven't already, we can capture the return value which
|
||||
// is in s1.
|
||||
// Left-hand case: we have moved element j into position. If we haven't
|
||||
// already, we can capture the return value which is in s1.
|
||||
//
|
||||
// Note: the STL breaks the loop into two just to avoid this
|
||||
// comparison once the return value is known. I'm not sure
|
||||
// it's a worthwhile optimization, though.
|
||||
// Note: the STL breaks the loop into two just to avoid this comparison
|
||||
// once the return value is known. I'm not sure it's a worthwhile
|
||||
// optimization, though.
|
||||
if ret == e { ret = s1 }
|
||||
|
||||
// If both regions were the same size, we're done.
|
||||
if s1 == m { break }
|
||||
}
|
||||
|
||||
// Now we have a smaller problem that is also a rotation, so we
|
||||
// can adjust our bounds and repeat.
|
||||
// Now we have a smaller problem that is also a rotation, so we can adjust
|
||||
// our bounds and repeat.
|
||||
//
|
||||
// h i j[d e f g|a b c] or d e f[a b c|g h i j]
|
||||
// ^ ^ ^ ^ ^ ^
|
||||
@@ -195,8 +193,8 @@ extension MutableCollection {
|
||||
return ret
|
||||
}
|
||||
|
||||
/// Rotates the elements of this collection so that the element
|
||||
/// at the specified index becomes the start of the collection.
|
||||
/// Rotates the elements of this collection so that the element at the
|
||||
/// specified index becomes the start of the collection.
|
||||
///
|
||||
/// Rotating a collection is equivalent to breaking the collection into two
|
||||
/// sections at the index `newStart`, and then swapping those two sections.
|
||||
@@ -221,8 +219,8 @@ extension MutableCollection {
|
||||
}
|
||||
|
||||
extension MutableCollection where Self: BidirectionalCollection {
|
||||
/// Rotates the elements within the given subrange so that the element
|
||||
/// at the specified index becomes the start of the subrange.
|
||||
/// Rotates the elements within the given subrange so that the element at the
|
||||
/// specified index becomes the start of the subrange.
|
||||
///
|
||||
/// Rotating a collection is equivalent to breaking the collection into two
|
||||
/// sections at the index `newStart`, and then swapping those two sections.
|
||||
@@ -255,13 +253,13 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
return newStart == p ? q : p
|
||||
}
|
||||
|
||||
/// Rotates the elements of this collection so that the element
|
||||
/// at the specified index becomes the start of the collection.
|
||||
/// Rotates the elements of this collection so that the element at the
|
||||
/// specified index becomes the start of the collection.
|
||||
///
|
||||
/// Rotating a collection is equivalent to breaking the collection into two
|
||||
/// sections at the index `newStart`, and then swapping those two sections.
|
||||
/// In this example, the `numbers` array is rotated so that the element at
|
||||
/// index `3` (`40`) is first:
|
||||
/// sections at the index `newStart`, and then swapping those two sections. In
|
||||
/// this example, the `numbers` array is rotated so that the element at index
|
||||
/// `3` (`40`) is first:
|
||||
///
|
||||
/// var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
|
||||
/// let oldStart = numbers.rotate(toStartAt: 3)
|
||||
@@ -279,22 +277,3 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
rotate(subrange: startIndex..<endIndex, toStartAt: newStart)
|
||||
}
|
||||
}
|
||||
|
||||
// Deprecations
|
||||
|
||||
extension MutableCollection {
|
||||
@available(*, deprecated, renamed: "rotate(subrange:toStartAt:)")
|
||||
@discardableResult
|
||||
public mutating func rotate(
|
||||
subrange: Range<Index>,
|
||||
at newStart: Index) -> Index
|
||||
{
|
||||
rotate(subrange: subrange, toStartAt: newStart)
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "rotate(toStartAt:)")
|
||||
@discardableResult
|
||||
public mutating func rotate(at newStart: Index) -> Index {
|
||||
rotate(toStartAt: newStart)
|
||||
}
|
||||
}
|
||||
@@ -10,8 +10,9 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// LazySplitSequence
|
||||
// SplitSequence
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A sequence that lazily splits a base sequence into subsequences separated by
|
||||
/// elements that satisfy the given `whereSeparator` predicate.
|
||||
///
|
||||
@@ -21,7 +22,7 @@
|
||||
/// x.split(separator:maxSplits:omittingEmptySubsequences)
|
||||
///
|
||||
/// where `x` conforms to `LazySequenceProtocol`.
|
||||
public struct LazySplitSequence<Base: Sequence> {
|
||||
public struct SplitSequence<Base: Sequence> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@@ -48,7 +49,7 @@ public struct LazySplitSequence<Base: Sequence> {
|
||||
}
|
||||
}
|
||||
|
||||
extension LazySplitSequence {
|
||||
extension SplitSequence: Sequence {
|
||||
public struct Iterator {
|
||||
public typealias Element = [Base.Element]
|
||||
|
||||
@@ -85,9 +86,19 @@ extension LazySplitSequence {
|
||||
self.omittingEmptySubsequences = omittingEmptySubsequences
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(
|
||||
base: base.makeIterator(),
|
||||
whereSeparator: self.isSeparator,
|
||||
maxSplits: self.maxSplits,
|
||||
omittingEmptySubsequences: self.omittingEmptySubsequences
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
extension LazySplitSequence.Iterator: IteratorProtocol {
|
||||
extension SplitSequence.Iterator: IteratorProtocol {
|
||||
@inlinable
|
||||
public mutating func next() -> Element? {
|
||||
var currentElement = base.next()
|
||||
@@ -128,17 +139,7 @@ extension LazySplitSequence.Iterator: IteratorProtocol {
|
||||
}
|
||||
}
|
||||
|
||||
extension LazySplitSequence: LazySequenceProtocol {
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
return Iterator(
|
||||
base: base.makeIterator(),
|
||||
whereSeparator: self.isSeparator,
|
||||
maxSplits: self.maxSplits,
|
||||
omittingEmptySubsequences: self.omittingEmptySubsequences
|
||||
)
|
||||
}
|
||||
}
|
||||
extension SplitSequence: LazySequenceProtocol {}
|
||||
|
||||
extension LazySequenceProtocol {
|
||||
/// Lazily returns the longest possible subsequences of the sequence, in
|
||||
@@ -230,10 +231,10 @@ extension LazySequenceProtocol {
|
||||
maxSplits: Int = Int.max,
|
||||
omittingEmptySubsequences: Bool = true,
|
||||
whereSeparator isSeparator: @escaping (Element) -> Bool
|
||||
) -> LazySplitSequence<Elements> {
|
||||
) -> SplitSequence<Elements> {
|
||||
precondition(maxSplits >= 0, "Must take zero or more splits")
|
||||
|
||||
return LazySplitSequence(
|
||||
return SplitSequence(
|
||||
base: elements,
|
||||
isSeparator: isSeparator,
|
||||
maxSplits: maxSplits,
|
||||
@@ -320,10 +321,10 @@ extension LazySequenceProtocol where Element: Equatable {
|
||||
separator: Element,
|
||||
maxSplits: Int = Int.max,
|
||||
omittingEmptySubsequences: Bool = true
|
||||
) -> LazySplitSequence<Elements> {
|
||||
) -> SplitSequence<Elements> {
|
||||
precondition(maxSplits >= 0, "Must take zero or more splits")
|
||||
|
||||
return LazySplitSequence(
|
||||
return SplitSequence(
|
||||
base: elements,
|
||||
isSeparator: { $0 == separator },
|
||||
maxSplits: maxSplits,
|
||||
@@ -333,8 +334,9 @@ extension LazySequenceProtocol where Element: Equatable {
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// LazySplitCollection
|
||||
// SplitCollection
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A collection that lazily splits a base collection into subsequences
|
||||
/// separated by elements that satisfy the given `whereSeparator` predicate.
|
||||
///
|
||||
@@ -343,8 +345,8 @@ extension LazySequenceProtocol where Element: Equatable {
|
||||
/// x.split(maxSplits:omittingEmptySubsequences:whereSeparator)
|
||||
/// x.split(separator:maxSplits:omittingEmptySubsequences)
|
||||
///
|
||||
/// where `x` conforms to `LazyCollectionProtocol`.
|
||||
public struct LazySplitCollection<Base: Collection> {
|
||||
/// where `x` conforms to `LazySequenceProtocol` and `Collection`.
|
||||
public struct SplitCollection<Base: Collection> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@@ -398,7 +400,7 @@ public struct LazySplitCollection<Base: Collection> {
|
||||
}
|
||||
}
|
||||
|
||||
extension LazySplitCollection: LazyCollectionProtocol {
|
||||
extension SplitCollection: Collection {
|
||||
/// Position of a subsequence in a split collection.
|
||||
public struct Index: Comparable {
|
||||
/// The range corresponding to the subsequence at this position.
|
||||
@@ -475,7 +477,7 @@ extension LazySplitCollection: LazyCollectionProtocol {
|
||||
}
|
||||
|
||||
var updatedSplitCount = splitCount
|
||||
if end < base.endIndex {
|
||||
if end != base.endIndex {
|
||||
// This subsequence ends on a separator (and perhaps includes other
|
||||
// separators, if we're omitting empty subsequences), so we've performed
|
||||
// another split.
|
||||
@@ -547,13 +549,16 @@ extension LazySplitCollection: LazyCollectionProtocol {
|
||||
}
|
||||
}
|
||||
|
||||
extension LazySplitCollection.Index: Hashable {
|
||||
extension SplitCollection.Index: Hashable {
|
||||
@inlinable
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(sequenceLength)
|
||||
}
|
||||
}
|
||||
|
||||
extension LazyCollectionProtocol {
|
||||
extension SplitCollection: LazyCollectionProtocol {}
|
||||
|
||||
extension LazySequenceProtocol where Self: Collection, Elements: Collection {
|
||||
/// Lazily returns the longest possible subsequences of the collection, in
|
||||
/// order, that don't contain elements satisfying the given predicate.
|
||||
///
|
||||
@@ -641,10 +646,10 @@ extension LazyCollectionProtocol {
|
||||
maxSplits: Int = Int.max,
|
||||
omittingEmptySubsequences: Bool = true,
|
||||
whereSeparator isSeparator: @escaping (Element) -> Bool
|
||||
) -> LazySplitCollection<Elements> {
|
||||
) -> SplitCollection<Elements> {
|
||||
precondition(maxSplits >= 0, "Must take zero or more splits")
|
||||
|
||||
return LazySplitCollection(
|
||||
return SplitCollection(
|
||||
base: elements,
|
||||
isSeparator: isSeparator,
|
||||
maxSplits: maxSplits,
|
||||
@@ -653,8 +658,9 @@ extension LazyCollectionProtocol {
|
||||
}
|
||||
}
|
||||
|
||||
extension LazyCollectionProtocol
|
||||
where Element: Equatable {
|
||||
extension LazySequenceProtocol
|
||||
where Self: Collection, Elements: Collection, Element: Equatable
|
||||
{
|
||||
/// Lazily returns the longest possible subsequences of the collection, in
|
||||
/// order, around elements equal to the given element.
|
||||
///
|
||||
@@ -737,10 +743,10 @@ where Element: Equatable {
|
||||
separator: Element,
|
||||
maxSplits: Int = Int.max,
|
||||
omittingEmptySubsequences: Bool = true
|
||||
) -> LazySplitCollection<Elements> {
|
||||
) -> SplitCollection<Elements> {
|
||||
precondition(maxSplits >= 0, "Must take zero or more splits")
|
||||
|
||||
return LazySplitCollection(
|
||||
return SplitCollection(
|
||||
base: elements,
|
||||
isSeparator: { $0 == separator },
|
||||
maxSplits: maxSplits,
|
||||
@@ -14,47 +14,46 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Sequence {
|
||||
/// Returns a sequence stepping through the elements every `step` starting
|
||||
/// at the first value. Any remainders of the stride will be trimmed.
|
||||
/// Returns a sequence stepping through the elements every `step` starting at
|
||||
/// the first value. Any remainders of the stride will be trimmed.
|
||||
///
|
||||
/// (0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10]
|
||||
/// (0...10).striding(by: 3) // == [0, 3, 6, 9]
|
||||
///
|
||||
/// - Complexity: O(1). Access to successive values is O(k) where
|
||||
/// _k_ is the striding `step`.
|
||||
/// - Complexity: O(1). Access to successive values is O(k) where _k_ is the
|
||||
/// striding `step`.
|
||||
///
|
||||
/// - Parameter step: The amount to step with each iteration.
|
||||
/// - Returns: Returns a sequence for stepping through the
|
||||
/// elements by the specified amount.
|
||||
/// - Returns: Returns a sequence for stepping through the elements by the
|
||||
/// specified amount.
|
||||
@inlinable
|
||||
public func striding(by step: Int) -> StrideSequence<Self> {
|
||||
StrideSequence(base: self, stride: step)
|
||||
public func striding(by step: Int) -> StridingSequence<Self> {
|
||||
StridingSequence(base: self, stride: step)
|
||||
}
|
||||
}
|
||||
|
||||
extension Collection {
|
||||
/// Returns a sequence stepping through the elements every `step` starting
|
||||
/// at the first value. Any remainders of the stride will be trimmed.
|
||||
/// Returns a sequence stepping through the elements every `step` starting at
|
||||
/// the first value. Any remainders of the stride will be trimmed.
|
||||
///
|
||||
/// (0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10]
|
||||
/// (0...10).striding(by: 3) // == [0, 3, 6, 9]
|
||||
///
|
||||
/// - Complexity: O(1). Access to successive values is O(1) if the
|
||||
/// collection conforms to `RandomAccessCollection`; otherwise,
|
||||
/// O(_k_), where _k_ is the striding `step`.
|
||||
/// - Complexity: O(1). Access to successive values is O(1) if the collection
|
||||
/// conforms to `RandomAccessCollection`; otherwise, O(_k_), where _k_ is
|
||||
/// the striding `step`.
|
||||
///
|
||||
/// - Parameter step: The amount to step with each iteration.
|
||||
/// - Returns: Returns a collection for stepping through the
|
||||
/// elements by the specified amount.
|
||||
/// - Returns: Returns a collection for stepping through the elements by the
|
||||
/// specified amount.
|
||||
@inlinable
|
||||
public func striding(by step: Int) -> StrideCollection<Self> {
|
||||
StrideCollection(base: self, stride: step)
|
||||
public func striding(by step: Int) -> StridingCollection<Self> {
|
||||
StridingCollection(base: self, stride: step)
|
||||
}
|
||||
}
|
||||
|
||||
/// A wrapper that strides over a base sequence.
|
||||
public struct StrideSequence<Base: Sequence>: Sequence {
|
||||
|
||||
public struct StridingSequence<Base: Sequence> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@@ -63,15 +62,21 @@ public struct StrideSequence<Base: Sequence>: Sequence {
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base, stride: Int) {
|
||||
precondition(stride > 0, "striding must be greater than zero")
|
||||
precondition(stride > 0, "Stride must be greater than zero")
|
||||
self.base = base
|
||||
self.stride = stride
|
||||
}
|
||||
}
|
||||
|
||||
extension StrideSequence {
|
||||
|
||||
/// An iterator over a `Stride` sequence.
|
||||
extension StridingSequence {
|
||||
@inlinable
|
||||
public func striding(by step: Int) -> Self {
|
||||
Self(base: base, stride: stride * step)
|
||||
}
|
||||
}
|
||||
|
||||
extension StridingSequence: Sequence {
|
||||
/// An iterator over a `StridingSequence` instance.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var iterator: Base.Iterator
|
||||
@@ -107,15 +112,11 @@ extension StrideSequence {
|
||||
}
|
||||
}
|
||||
|
||||
extension StrideSequence {
|
||||
@inlinable
|
||||
public func striding(by step: Int) -> Self {
|
||||
Self(base: base, stride: stride * step)
|
||||
}
|
||||
}
|
||||
extension StridingSequence: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
/// A wrapper that strides over a base collection.
|
||||
public struct StrideCollection<Base: Collection> {
|
||||
public struct StridingCollection<Base: Collection> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@@ -130,16 +131,15 @@ public struct StrideCollection<Base: Collection> {
|
||||
}
|
||||
}
|
||||
|
||||
extension StrideCollection {
|
||||
extension StridingCollection {
|
||||
@inlinable
|
||||
public func striding(by step: Int) -> Self {
|
||||
Self(base: base, stride: stride * step)
|
||||
}
|
||||
}
|
||||
|
||||
extension StrideCollection: Collection {
|
||||
|
||||
/// A position in a `Stride` collection.
|
||||
extension StridingCollection: Collection {
|
||||
/// A position in a `StridingCollection` instance.
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal let base: Base.Index
|
||||
@@ -172,7 +172,7 @@ extension StrideCollection: Collection {
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> Index {
|
||||
precondition(i.base < base.endIndex, "Advancing past end index")
|
||||
precondition(i.base != base.endIndex, "Advancing past end index")
|
||||
return index(i, offsetBy: 1)
|
||||
}
|
||||
|
||||
@@ -226,9 +226,15 @@ extension StrideCollection: Collection {
|
||||
offsetBy n: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
let distance = i == endIndex
|
||||
? -((base.count - 1) % stride + 1) + (n - 1) * -stride
|
||||
: n * -stride
|
||||
// We typically use the ternary operator but this significantly increases
|
||||
// compile times when using Swift 5.3.2
|
||||
// https://github.com/apple/swift-algorithms/issues/146
|
||||
let distance: Int
|
||||
if i == endIndex {
|
||||
distance = -((base.count - 1) % stride + 1) + (n - 1) * -stride
|
||||
} else {
|
||||
distance = n * -stride
|
||||
}
|
||||
return base.index(
|
||||
i.base,
|
||||
offsetBy: distance,
|
||||
@@ -249,8 +255,8 @@ extension StrideCollection: Collection {
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||
precondition(distance <= 0 || i.base < base.endIndex, "Advancing past end index")
|
||||
precondition(distance >= 0 || i.base > base.startIndex, "Incrementing past start index")
|
||||
precondition(distance <= 0 || i.base != base.endIndex, "Advancing past end index")
|
||||
precondition(distance >= 0 || i.base != base.startIndex, "Incrementing past start index")
|
||||
let limit = distance > 0 ? endIndex : startIndex
|
||||
let idx = index(i, offsetBy: distance, limitedBy: limit)
|
||||
precondition(idx != nil, "The distance \(distance) is not valid for this collection")
|
||||
@@ -258,33 +264,20 @@ extension StrideCollection: Collection {
|
||||
}
|
||||
}
|
||||
|
||||
extension StrideCollection: BidirectionalCollection
|
||||
extension StridingCollection: BidirectionalCollection
|
||||
where Base: RandomAccessCollection {
|
||||
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
precondition(i.base > base.startIndex, "Incrementing past start index")
|
||||
precondition(i.base != base.startIndex, "Incrementing past start index")
|
||||
return index(i, offsetBy: -1)
|
||||
}
|
||||
}
|
||||
|
||||
extension StrideCollection: RandomAccessCollection where Base: RandomAccessCollection {}
|
||||
extension StridingCollection: RandomAccessCollection
|
||||
where Base: RandomAccessCollection {}
|
||||
|
||||
extension StrideCollection: Equatable where Base.Element: Equatable {
|
||||
@inlinable
|
||||
public static func == (lhs: StrideCollection, rhs: StrideCollection) -> Bool {
|
||||
lhs.elementsEqual(rhs, by: ==)
|
||||
}
|
||||
}
|
||||
extension StridingCollection: LazySequenceProtocol, LazyCollectionProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
extension StrideCollection: Hashable where Base.Element: Hashable {
|
||||
@inlinable
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(stride)
|
||||
for element in self {
|
||||
hasher.combine(element)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension StrideCollection.Index: Hashable where Base.Index: Hashable {}
|
||||
extension StridingCollection.Index: Hashable where Base.Index: Hashable {}
|
||||
@@ -17,10 +17,10 @@ extension BidirectionalCollection {
|
||||
/// Returns a subsequence containing the elements from the end until
|
||||
/// `predicate` returns `false` and skipping the remaining elements.
|
||||
///
|
||||
/// - Parameter predicate: A closure that takes an element of the
|
||||
/// sequence as its argument and returns `true` if the element should
|
||||
/// be included or `false` if it should be excluded. Once the predicate
|
||||
/// returns `false` it will not be called again.
|
||||
/// - Parameter predicate: A closure that takes an element of the sequence as
|
||||
/// its argument and returns `true` if the element should be included or
|
||||
/// `false` if it should be excluded. Once the predicate returns `false` it
|
||||
/// will not be called again.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
|
||||
@@ -7,6 +7,91 @@
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// trimmingPrefix(while:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Collection {
|
||||
/// Returns a `SubSequence` formed by discarding all elements at the start of
|
||||
/// the collection which satisfy the given predicate.
|
||||
///
|
||||
/// This example uses `trimmingPrefix(while:)` to get a substring without the
|
||||
/// white space at the beginning of the string:
|
||||
///
|
||||
/// let myString = " hello, world "
|
||||
/// print(myString.trimmingPrefix(while: \.isWhitespace)) // "hello, world "
|
||||
///
|
||||
/// - Parameter predicate: A closure which determines if the element should be
|
||||
/// omitted from the resulting slice.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
///
|
||||
@inlinable
|
||||
public func trimmingPrefix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> SubSequence {
|
||||
let start = try endOfPrefix(while: predicate)
|
||||
return self[start...]
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// trimPrefix(while:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Collection where Self: RangeReplaceableCollection {
|
||||
/// Mutates a `Collection` by discarding all elements at the start of it which
|
||||
/// satisfy the given predicate.
|
||||
///
|
||||
/// This example uses `trimPrefix(while:)` to remove the white space at the
|
||||
/// beginning of the string:
|
||||
///
|
||||
/// let myString = " hello, world "
|
||||
/// myString.trimPrefix(while: \.isWhitespace)
|
||||
/// print(myString) // "hello, world "
|
||||
///
|
||||
/// - Parameter predicate: A closure which determines if the element should be
|
||||
/// removed from the string.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
///
|
||||
@inlinable
|
||||
@_disfavoredOverload
|
||||
public mutating func trimPrefix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows {
|
||||
let end = try endOfPrefix(while: predicate)
|
||||
removeSubrange(startIndex..<end)
|
||||
}
|
||||
}
|
||||
|
||||
extension Collection where Self == Self.SubSequence {
|
||||
/// Mutates a `Collection` by discarding all elements at the start of it which
|
||||
/// satisfy the given predicate.
|
||||
///
|
||||
/// This example uses `trimPrefix(while:)` to remove the white space at the
|
||||
/// beginning of the string:
|
||||
///
|
||||
/// let myString = " hello, world "
|
||||
/// myString.trimPrefix(while: \.isWhitespace)
|
||||
/// print(myString) // "hello, world "
|
||||
///
|
||||
/// - Parameters predicate: A closure which determines if the element should
|
||||
/// be removed from the string.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
///
|
||||
@inlinable
|
||||
public mutating func trimPrefix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows {
|
||||
self = try trimmingPrefix(while: predicate)
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// trimming(while:) / trimmingSuffix(while:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension BidirectionalCollection {
|
||||
@@ -19,9 +104,8 @@ extension BidirectionalCollection {
|
||||
/// let myString = " hello, world "
|
||||
/// print(myString.trimming(while: \.isWhitespace)) // "hello, world"
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - predicate: A closure which determines if the element should be
|
||||
/// omitted from the resulting slice.
|
||||
/// - Parameter predicate: A closure which determines if the element should be
|
||||
/// omitted from the resulting slice.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
///
|
||||
@@ -29,8 +113,128 @@ extension BidirectionalCollection {
|
||||
public func trimming(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> SubSequence {
|
||||
let start = try endOfPrefix(while: predicate)
|
||||
let end = try self[start...].startOfSuffix(while: predicate)
|
||||
return self[start..<end]
|
||||
try trimmingPrefix(while: predicate).trimmingSuffix(while: predicate)
|
||||
}
|
||||
|
||||
/// Returns a `SubSequence` formed by discarding all elements at the end of
|
||||
/// the collection which satisfy the given predicate.
|
||||
///
|
||||
/// This example uses `trimmingSuffix(while:)` to get a substring without the
|
||||
/// white space at the end of the string:
|
||||
///
|
||||
/// let myString = " hello, world "
|
||||
/// print(myString.trimmingSuffix(while: \.isWhitespace)) // " hello, world"
|
||||
///
|
||||
/// - Parameter predicate: A closure which determines if the element should be
|
||||
/// omitted from the resulting slice.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
///
|
||||
@inlinable
|
||||
public func trimmingSuffix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> SubSequence {
|
||||
let end = try startOfSuffix(while: predicate)
|
||||
return self[..<end]
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// trim(while:) / trimSuffix(while:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension BidirectionalCollection where Self: RangeReplaceableCollection {
|
||||
/// Mutates a `BidirectionalCollection` by discarding all elements at the
|
||||
/// start and at the end of it which satisfy the given predicate.
|
||||
///
|
||||
/// This example uses `trim(while:)` to remove the white space at the
|
||||
/// beginning of the string:
|
||||
///
|
||||
/// let myString = " hello, world "
|
||||
/// myString.trim(while: \.isWhitespace)
|
||||
/// print(myString) // "hello, world"
|
||||
///
|
||||
/// - Parameter predicate: A closure which determines if the element should be
|
||||
/// removed from the string.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
///
|
||||
@inlinable
|
||||
@_disfavoredOverload
|
||||
public mutating func trim(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows {
|
||||
try trimSuffix(while: predicate)
|
||||
try trimPrefix(while: predicate)
|
||||
}
|
||||
|
||||
/// Mutates a `BidirectionalCollection` by discarding all elements at the end
|
||||
/// of it which satisfy the given predicate.
|
||||
///
|
||||
/// This example uses `trimSuffix(while:)` to remove the white space at the
|
||||
/// beginning of the string:
|
||||
///
|
||||
/// let myString = " hello, world "
|
||||
/// myString.trimSuffix(while: \.isWhitespace)
|
||||
/// print(myString) // " hello, world"
|
||||
///
|
||||
/// - Parameter predicate: A closure which determines if the element should be
|
||||
/// removed from the string.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
///
|
||||
@inlinable
|
||||
@_disfavoredOverload
|
||||
public mutating func trimSuffix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows {
|
||||
let start = try startOfSuffix(while: predicate)
|
||||
removeSubrange(start..<endIndex)
|
||||
}
|
||||
}
|
||||
|
||||
extension BidirectionalCollection where Self == Self.SubSequence {
|
||||
/// Mutates a `BidirectionalCollection` by discarding all elements at the
|
||||
/// start and at the end of it which satisfy the given predicate.
|
||||
///
|
||||
/// This example uses `trim(while:)` to remove the white space at the
|
||||
/// beginning of the string:
|
||||
///
|
||||
/// let myString = " hello, world "
|
||||
/// myString.trim(while: \.isWhitespace)
|
||||
/// print(myString) // "hello, world"
|
||||
///
|
||||
/// - Parameter predicate: A closure which determines if the element should be
|
||||
/// removed from the string.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
///
|
||||
@inlinable
|
||||
public mutating func trim(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows {
|
||||
self = try trimming(while: predicate)
|
||||
}
|
||||
|
||||
/// Mutates a `BidirectionalCollection` by discarding all elements at the end
|
||||
/// of it which satisfy the given predicate.
|
||||
///
|
||||
/// This example uses `trimSuffix(while:)` to remove the white space at the
|
||||
/// beginning of the string:
|
||||
///
|
||||
/// let myString = " hello, world "
|
||||
/// myString.trimSuffix(while: \.isWhitespace)
|
||||
/// print(myString) // " hello, world"
|
||||
///
|
||||
/// - Parameter predicate: A closure which determines if the element should be
|
||||
/// removed from the string.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
///
|
||||
@inlinable
|
||||
public mutating func trimSuffix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows {
|
||||
self = try trimmingSuffix(while: predicate)
|
||||
}
|
||||
}
|
||||
@@ -9,25 +9,83 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A sequence wrapper that leaves out duplicate elements of a base sequence.
|
||||
public struct UniquedSequence<Base: Sequence, Subject: Hashable> {
|
||||
/// The base collection.
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
/// The projection function.
|
||||
@usableFromInline
|
||||
internal let projection: (Base.Element) -> Subject
|
||||
|
||||
@usableFromInline
|
||||
internal init(base: Base, projection: @escaping (Base.Element) -> Subject) {
|
||||
self.base = base
|
||||
self.projection = projection
|
||||
}
|
||||
}
|
||||
|
||||
extension UniquedSequence: Sequence {
|
||||
/// The iterator for a `UniquedSequence` instance.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var base: Base.Iterator
|
||||
|
||||
@usableFromInline
|
||||
internal let projection: (Base.Element) -> Subject
|
||||
|
||||
@usableFromInline
|
||||
internal var seen: Set<Subject> = []
|
||||
|
||||
@usableFromInline
|
||||
internal init(
|
||||
base: Base.Iterator,
|
||||
projection: @escaping (Base.Element) -> Subject
|
||||
) {
|
||||
self.base = base
|
||||
self.projection = projection
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Base.Element? {
|
||||
while let element = base.next() {
|
||||
if seen.insert(projection(element)).inserted {
|
||||
return element
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(base: base.makeIterator(), projection: projection)
|
||||
}
|
||||
}
|
||||
|
||||
extension UniquedSequence: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// uniqued()
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Sequence where Element: Hashable {
|
||||
/// Returns an array with only the unique elements of this sequence, in the
|
||||
/// Returns a sequence with only the unique elements of this sequence, in the
|
||||
/// order of the first occurrence of each unique element.
|
||||
///
|
||||
/// let animals = ["dog", "pig", "cat", "ox", "dog", "cat"]
|
||||
/// let uniqued = animals.uniqued()
|
||||
/// print(uniqued)
|
||||
/// print(Array(uniqued))
|
||||
/// // Prints '["dog", "pig", "cat", "ox"]'
|
||||
///
|
||||
/// - Returns: An array with only the unique elements of this sequence.
|
||||
/// - Returns: A sequence with only the unique elements of this sequence.
|
||||
/// .
|
||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
||||
/// - Complexity: O(1).
|
||||
@inlinable
|
||||
public func uniqued() -> [Element] {
|
||||
uniqued(on: { $0 })
|
||||
public func uniqued() -> UniquedSequence<Self, Element> {
|
||||
UniquedSequence(base: self, projection: { $0 })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,14 +98,14 @@ extension Sequence {
|
||||
/// first characters:
|
||||
///
|
||||
/// let animals = ["dog", "pig", "cat", "ox", "cow", "owl"]
|
||||
/// let uniqued = animals.uniqued(on: {$0.first})
|
||||
/// let uniqued = animals.uniqued(on: { $0.first })
|
||||
/// print(uniqued)
|
||||
/// // Prints '["dog", "pig", "cat", "ox"]'
|
||||
///
|
||||
/// - Parameter projection: A closure that transforms an element into the
|
||||
/// value to use for uniqueness. If `projection` returns the same value
|
||||
/// for two different elements, the second element will be excluded
|
||||
/// from the resulting array.
|
||||
/// value to use for uniqueness. If `projection` returns the same value for
|
||||
/// two different elements, the second element will be excluded from the
|
||||
/// resulting array.
|
||||
///
|
||||
/// - Returns: An array with only the unique elements of this sequence, as
|
||||
/// determined by the result of `projection` for each element.
|
||||
@@ -67,3 +125,21 @@ extension Sequence {
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// lazy.uniqued()
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension LazySequenceProtocol {
|
||||
/// Returns a lazy sequence with the unique elements of this sequence (as
|
||||
/// determined by the given projection), in the order of the first occurrence
|
||||
/// of each unique element.
|
||||
///
|
||||
/// - Complexity: O(1).
|
||||
@inlinable
|
||||
public func uniqued<Subject: Hashable>(
|
||||
on projection: @escaping (Element) -> Subject
|
||||
) -> UniquedSequence<Self, Subject> {
|
||||
UniquedSequence(base: self, projection: projection)
|
||||
}
|
||||
}
|
||||
@@ -39,32 +39,35 @@ extension Collection {
|
||||
/// `RandomAccessCollection`, otherwise O(*k*) where `k` is `count`.
|
||||
/// Access to successive windows is O(1).
|
||||
@inlinable
|
||||
public func windows(ofCount count: Int) -> Windows<Self> {
|
||||
Windows(base: self, size: count)
|
||||
public func windows(ofCount count: Int) -> WindowsOfCountCollection<Self> {
|
||||
WindowsOfCountCollection(base: self, windowSize: count)
|
||||
}
|
||||
}
|
||||
|
||||
/// A collection wrapper that presents a sliding window over the elements of
|
||||
/// a collection.
|
||||
public struct Windows<Base: Collection> {
|
||||
public let base: Base
|
||||
public let size: Int
|
||||
public struct WindowsOfCountCollection<Base: Collection> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal var firstUpperBound: Base.Index?
|
||||
internal let windowSize: Int
|
||||
|
||||
@usableFromInline
|
||||
internal var endOfFirstWindow: Base.Index?
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base, size: Int) {
|
||||
precondition(size > 0, "Windows size must be greater than zero")
|
||||
internal init(base: Base, windowSize: Int) {
|
||||
precondition(windowSize > 0, "Windows size must be greater than zero")
|
||||
self.base = base
|
||||
self.size = size
|
||||
self.firstUpperBound =
|
||||
base.index(base.startIndex, offsetBy: size, limitedBy: base.endIndex)
|
||||
self.windowSize = windowSize
|
||||
self.endOfFirstWindow =
|
||||
base.index(base.startIndex, offsetBy: windowSize, limitedBy: base.endIndex)
|
||||
}
|
||||
}
|
||||
|
||||
extension Windows: Collection {
|
||||
/// A position in a `Windows` collection.
|
||||
extension WindowsOfCountCollection: Collection {
|
||||
/// A position in a `WindowsOfCountCollection` instance.
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal var lowerBound: Base.Index
|
||||
@@ -91,7 +94,7 @@ extension Windows: Collection {
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
if let upperBound = firstUpperBound {
|
||||
if let upperBound = endOfFirstWindow {
|
||||
return Index(lowerBound: base.startIndex, upperBound: upperBound)
|
||||
} else {
|
||||
return endIndex
|
||||
@@ -113,12 +116,14 @@ extension Windows: Collection {
|
||||
|
||||
@inlinable
|
||||
public func index(after index: Index) -> Index {
|
||||
precondition(index < endIndex, "Advancing past end index")
|
||||
precondition(index != endIndex, "Advancing past end index")
|
||||
guard index.upperBound < base.endIndex else { return endIndex }
|
||||
return Index(
|
||||
lowerBound: base.index(after: index.lowerBound),
|
||||
upperBound: base.index(after: index.upperBound)
|
||||
)
|
||||
|
||||
let lowerBound = windowSize == 1
|
||||
? index.upperBound
|
||||
: base.index(after: index.lowerBound)
|
||||
let upperBound = base.index(after: index.upperBound)
|
||||
return Index(lowerBound: lowerBound, upperBound: upperBound)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@@ -182,7 +187,7 @@ extension Windows: Collection {
|
||||
// |> > >|>| or |> > >|
|
||||
// output: [x x x x x|x x x x x] [x x x x x x x x x x] (`endIndex`)
|
||||
|
||||
if distance >= size {
|
||||
if distance >= windowSize {
|
||||
// Avoid traversing `self[i.lowerBound..<i.upperBound]` when the lower
|
||||
// bound of the output is greater than or equal to the upper bound of the
|
||||
// input.
|
||||
@@ -194,11 +199,11 @@ extension Windows: Collection {
|
||||
guard limit.lowerBound >= i.upperBound,
|
||||
let lowerBound = base.index(
|
||||
i.upperBound,
|
||||
offsetBy: distance - size,
|
||||
offsetBy: distance - windowSize,
|
||||
limitedBy: limit.lowerBound),
|
||||
let indexBeforeUpperBound = base.index(
|
||||
lowerBound,
|
||||
offsetBy: size - 1,
|
||||
offsetBy: windowSize - 1,
|
||||
limitedBy: limit.upperBound)
|
||||
else { return nil }
|
||||
|
||||
@@ -259,9 +264,9 @@ extension Windows: Collection {
|
||||
else { return nil }
|
||||
|
||||
return Index(
|
||||
lowerBound: base.index(upperBound, offsetBy: -size),
|
||||
lowerBound: base.index(upperBound, offsetBy: -windowSize),
|
||||
upperBound: upperBound)
|
||||
} else if distance >= size {
|
||||
} else if distance >= windowSize {
|
||||
// Avoid traversing `self[i.lowerBound..<i.upperBound]` when the upper
|
||||
// bound of the output is less than or equal to the lower bound of the
|
||||
// input.
|
||||
@@ -273,12 +278,12 @@ extension Windows: Collection {
|
||||
guard limit.upperBound <= i.lowerBound,
|
||||
let upperBound = base.index(
|
||||
i.lowerBound,
|
||||
offsetBy: -(distance - size),
|
||||
offsetBy: -(distance - windowSize),
|
||||
limitedBy: limit.upperBound)
|
||||
else { return nil }
|
||||
|
||||
return Index(
|
||||
lowerBound: base.index(upperBound, offsetBy: -size),
|
||||
lowerBound: base.index(upperBound, offsetBy: -windowSize),
|
||||
upperBound: upperBound)
|
||||
} else {
|
||||
// input: [x x x x x|x x x x x x|x]
|
||||
@@ -301,7 +306,7 @@ extension Windows: Collection {
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
guard start <= end else { return -distance(from: end, to: start) }
|
||||
guard start != end else { return 0 }
|
||||
guard end < endIndex else {
|
||||
guard end != endIndex else {
|
||||
// We add 1 here because the index before `endIndex` also has
|
||||
// `base.endIndex` as its upper bound.
|
||||
return base[start.upperBound...].count + 1
|
||||
@@ -315,7 +320,7 @@ extension Windows: Collection {
|
||||
// |- - - -|> >|
|
||||
// end: [x x x x x x x|x x x x|x]
|
||||
|
||||
return size + base[start.upperBound..<end.lowerBound].count
|
||||
return windowSize + base[start.upperBound..<end.lowerBound].count
|
||||
} else {
|
||||
// start: [x|x x x x x x|x x x x x]
|
||||
// |> > > >|
|
||||
@@ -326,13 +331,15 @@ extension Windows: Collection {
|
||||
}
|
||||
}
|
||||
|
||||
extension Windows: BidirectionalCollection where Base: BidirectionalCollection {
|
||||
extension WindowsOfCountCollection: BidirectionalCollection
|
||||
where Base: BidirectionalCollection
|
||||
{
|
||||
@inlinable
|
||||
public func index(before index: Index) -> Index {
|
||||
precondition(index > startIndex, "Incrementing past start index")
|
||||
precondition(index != startIndex, "Incrementing past start index")
|
||||
if index == endIndex {
|
||||
return Index(
|
||||
lowerBound: base.index(index.lowerBound, offsetBy: -size),
|
||||
lowerBound: base.index(index.lowerBound, offsetBy: -windowSize),
|
||||
upperBound: index.upperBound
|
||||
)
|
||||
} else {
|
||||
@@ -344,9 +351,10 @@ extension Windows: BidirectionalCollection where Base: BidirectionalCollection {
|
||||
}
|
||||
}
|
||||
|
||||
extension Windows: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
extension Windows: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
|
||||
extension Windows: RandomAccessCollection where Base: RandomAccessCollection {}
|
||||
extension Windows: Equatable where Base: Equatable {}
|
||||
extension Windows: Hashable where Base: Hashable, Base.Index: Hashable {}
|
||||
extension Windows.Index: Hashable where Base.Index: Hashable {}
|
||||
extension WindowsOfCountCollection: RandomAccessCollection
|
||||
where Base: RandomAccessCollection {}
|
||||
|
||||
extension WindowsOfCountCollection: LazySequenceProtocol, LazyCollectionProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
extension WindowsOfCountCollection.Index: Hashable where Base.Index: Hashable {}
|
||||
@@ -1,19 +0,0 @@
|
||||
//===----------------------------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Argument Parser open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#error("""
|
||||
|
||||
-----------------------------------------------------
|
||||
|
||||
Please test with `swift test --enable-test-discovery`
|
||||
|
||||
-----------------------------------------------------
|
||||
""")
|
||||
@@ -0,0 +1,84 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Algorithms
|
||||
|
||||
final class AdjacentPairsTests: XCTestCase {
|
||||
func testEmptySequence() {
|
||||
let pairs = (0...).prefix(0).adjacentPairs()
|
||||
XCTAssertEqualSequences(pairs, [], by: ==)
|
||||
}
|
||||
|
||||
func testOneElementSequence() {
|
||||
let pairs = (0...).prefix(1).adjacentPairs()
|
||||
XCTAssertEqualSequences(pairs, [], by: ==)
|
||||
}
|
||||
|
||||
func testTwoElementSequence() {
|
||||
let pairs = (0...).prefix(2).adjacentPairs()
|
||||
XCTAssertEqualSequences(pairs, [(0, 1)], by: ==)
|
||||
}
|
||||
|
||||
func testThreeElementSequence() {
|
||||
let pairs = (0...).prefix(3).adjacentPairs()
|
||||
XCTAssertEqualSequences(pairs, [(0, 1), (1, 2)], by: ==)
|
||||
}
|
||||
|
||||
func testManySequences() {
|
||||
for n in 4...100 {
|
||||
let pairs = (0...).prefix(n).adjacentPairs()
|
||||
XCTAssertEqualSequences(pairs, zip(0..., 1...).prefix(n - 1), by: ==)
|
||||
}
|
||||
}
|
||||
|
||||
func testZeroElements() {
|
||||
let pairs = (0..<0).adjacentPairs()
|
||||
XCTAssertEqual(pairs.startIndex, pairs.endIndex)
|
||||
XCTAssertEqualSequences(pairs, [], by: ==)
|
||||
}
|
||||
|
||||
func testOneElement() {
|
||||
let pairs = (0..<1).adjacentPairs()
|
||||
XCTAssertEqual(pairs.startIndex, pairs.endIndex)
|
||||
XCTAssertEqualSequences(pairs, [], by: ==)
|
||||
}
|
||||
|
||||
func testTwoElements() {
|
||||
let pairs = (0..<2).adjacentPairs()
|
||||
XCTAssertEqualSequences(pairs, [(0, 1)], by: ==)
|
||||
}
|
||||
|
||||
func testThreeElements() {
|
||||
let pairs = (0..<3).adjacentPairs()
|
||||
XCTAssertEqualSequences(pairs, [(0, 1), (1, 2)], by: ==)
|
||||
}
|
||||
|
||||
func testManyElements() {
|
||||
for n in 4...100 {
|
||||
let pairs = (0..<n).adjacentPairs()
|
||||
XCTAssertEqualSequences(pairs, zip(0..., 1...).prefix(n - 1), by: ==)
|
||||
}
|
||||
}
|
||||
|
||||
func testIndexTraversals() {
|
||||
let validator = IndexValidator<AdjacentPairsCollection<Range<Int>>>()
|
||||
validator.validate((0..<0).adjacentPairs(), expectedCount: 0)
|
||||
validator.validate((0..<1).adjacentPairs(), expectedCount: 0)
|
||||
validator.validate((0..<2).adjacentPairs(), expectedCount: 1)
|
||||
validator.validate((0..<5).adjacentPairs(), expectedCount: 4)
|
||||
}
|
||||
|
||||
func testLaziness() {
|
||||
XCTAssertLazySequence((0...).lazy.adjacentPairs())
|
||||
XCTAssertLazyCollection((0..<100).lazy.adjacentPairs())
|
||||
}
|
||||
}
|
||||
@@ -36,16 +36,17 @@ final class ChainTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testChainIndexTraversals() {
|
||||
validateIndexTraversals(
|
||||
chain("abcd", "XYZ"),
|
||||
chain("abcd", ""),
|
||||
chain("", "XYZ"),
|
||||
chain("", ""),
|
||||
indices: { chain in
|
||||
let validator = IndexValidator<Chain2Sequence<String, String>>(
|
||||
indicesIncludingEnd: { chain in
|
||||
chain.base1.indices.map { .init(first: $0) }
|
||||
+ chain.base2.indices.map { .init(second: $0) }
|
||||
+ [.init(second: chain.base2.endIndex)]
|
||||
})
|
||||
|
||||
validator.validate(chain("abcd", "XYZ"), expectedCount: 4 + 3)
|
||||
validator.validate(chain("abcd", ""), expectedCount: 4 + 0)
|
||||
validator.validate(chain("", "XYZ"), expectedCount: 0 + 3)
|
||||
validator.validate(chain("", ""), expectedCount: 0 + 0)
|
||||
}
|
||||
|
||||
func testChainIndexOffsetAcrossBoundary() {
|
||||
|
||||
@@ -47,8 +47,12 @@ final class ChunkedTests: XCTestCase {
|
||||
func testSimple() {
|
||||
// Example
|
||||
let names = ["David", "Kyle", "Karoy", "Nate"]
|
||||
let chunks = names.chunked(on: { $0.first })
|
||||
XCTAssertEqualSequences([["David"], ["Kyle", "Karoy"], ["Nate"]], chunks)
|
||||
let chunks = names.chunked(on: { $0.first! })
|
||||
let expected: [(Character, ArraySlice<String>)] = [
|
||||
("D", ["David"]),
|
||||
("K", ["Kyle", "Karoy"]),
|
||||
("N", ["Nate"])]
|
||||
XCTAssertEqualSequences(expected, chunks, by: ==)
|
||||
|
||||
// Empty sequence
|
||||
XCTAssertEqual(0, names.prefix(0).chunked(on: { $0.first }).count)
|
||||
@@ -59,10 +63,11 @@ final class ChunkedTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testChunkedOn() {
|
||||
validateFruitChunks(fruits.chunked(on: { $0.first }))
|
||||
validateFruitChunks(fruits.chunked(on: { $0.first }).map { $1 })
|
||||
|
||||
let lazyChunks = fruits.lazy.chunked(on: { $0.first })
|
||||
validateFruitChunks(lazyChunks)
|
||||
validateFruitChunks(lazyChunks.map { $1 })
|
||||
IndexValidator().validate(lazyChunks)
|
||||
}
|
||||
|
||||
func testChunkedBy() {
|
||||
@@ -70,6 +75,23 @@ final class ChunkedTests: XCTestCase {
|
||||
|
||||
let lazyChunks = fruits.lazy.chunked(by: { $0.first == $1.first })
|
||||
validateFruitChunks(lazyChunks)
|
||||
IndexValidator().validate(lazyChunks)
|
||||
}
|
||||
|
||||
func testChunkedByComparesConsecutiveElements() {
|
||||
XCTAssertEqualSequences(
|
||||
[1, 2, 3, 4, 6, 7, 8, 9].chunked(by: { $1 - $0 == 1 }),
|
||||
[[1, 2, 3, 4], [6, 7, 8, 9]])
|
||||
|
||||
XCTAssertEqualSequences(
|
||||
[1, 2, 3, 4, 6, 7, 8, 9].lazy.chunked(by: { $1 - $0 == 1 }),
|
||||
[[1, 2, 3, 4], [6, 7, 8, 9]])
|
||||
|
||||
XCTAssertEqualSequences(
|
||||
[1, 2, 3, 4, 6, 7, 8, 9].lazy.chunked(by: { $1 - $0 == 1 }).reversed(),
|
||||
[[6, 7, 8, 9], [1, 2, 3, 4]])
|
||||
|
||||
IndexValidator().validate([1, 2, 3].lazy.chunked(by: { $1 - $0 == 1 }))
|
||||
}
|
||||
|
||||
func testChunkedLazy() {
|
||||
@@ -77,10 +99,10 @@ final class ChunkedTests: XCTestCase {
|
||||
XCTAssertLazySequence(fruits.lazy.chunked(on: { $0.first }))
|
||||
}
|
||||
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Tests for `chunks(ofCount:)`
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
func testChunksOfCount() {
|
||||
XCTAssertEqualSequences([Int]().chunks(ofCount: 1), [])
|
||||
XCTAssertEqualSequences([Int]().chunks(ofCount: 5), [])
|
||||
@@ -134,15 +156,51 @@ final class ChunkedTests: XCTestCase {
|
||||
func testEmptyChunksOfCountTraversal() {
|
||||
let emptyChunks = [Int]().chunks(ofCount: 1)
|
||||
|
||||
validateIndexTraversals(emptyChunks)
|
||||
IndexValidator().validate(emptyChunks, expectedCount: 0)
|
||||
}
|
||||
|
||||
func testChunksOfCountTraversal() {
|
||||
for i in 1..<10 {
|
||||
let collection = (1...50).map { $0 }
|
||||
let chunks = collection.chunks(ofCount: i)
|
||||
|
||||
validateIndexTraversals(chunks)
|
||||
let validator = IndexValidator<ChunksOfCountCollection<ClosedRange<Int>>>()
|
||||
|
||||
for i in 1...10 {
|
||||
let range = 1...50
|
||||
let chunks = range.chunks(ofCount: i)
|
||||
validator.validate(
|
||||
chunks,
|
||||
expectedCount: range.count / i + (range.count % i).signum())
|
||||
}
|
||||
}
|
||||
|
||||
func testEvenChunks() {
|
||||
XCTAssertEqualSequences(
|
||||
(0..<10).evenlyChunked(in: 4),
|
||||
[0..<3, 3..<6, 6..<8, 8..<10])
|
||||
|
||||
XCTAssertEqualSequences(
|
||||
(0..<3).evenlyChunked(in: 5),
|
||||
[0..<1, 1..<2, 2..<3, 3..<3, 3..<3])
|
||||
|
||||
XCTAssertEqualSequences(
|
||||
"".evenlyChunked(in: 0),
|
||||
[])
|
||||
|
||||
XCTAssertEqualSequences(
|
||||
"".evenlyChunked(in: 1),
|
||||
[""])
|
||||
}
|
||||
|
||||
func testEvenChunksIndexTraversals() {
|
||||
let validator = IndexValidator<EvenlyChunkedCollection<Range<Int>>>()
|
||||
|
||||
[
|
||||
(0..<10).evenlyChunked(in: 1),
|
||||
(0..<10).evenlyChunked(in: 2),
|
||||
(0..<10).evenlyChunked(in: 3),
|
||||
(0..<10).evenlyChunked(in: 10),
|
||||
(0..<10).evenlyChunked(in: 20),
|
||||
(0..<0).evenlyChunked(in: 0),
|
||||
(0..<0).evenlyChunked(in: 1),
|
||||
(0..<0).evenlyChunked(in: 10),
|
||||
].forEach { validator.validate($0) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Algorithms
|
||||
|
||||
final class CompactedTests: XCTestCase {
|
||||
|
||||
let tests: [[Int?]] =
|
||||
[nil, nil, nil, 0, 1, 2]
|
||||
.uniquePermutations(ofCount: 0...)
|
||||
.map(Array.init)
|
||||
|
||||
func testCompactedCompacted() {
|
||||
for collection in self.tests {
|
||||
let seq = AnySequence(collection)
|
||||
XCTAssertEqualSequences(
|
||||
seq.compactMap({ $0 }), seq.compacted())
|
||||
XCTAssertEqualSequences(
|
||||
collection.compactMap({ $0 }), collection.compacted())
|
||||
}
|
||||
}
|
||||
|
||||
func testCompactedBidirectionalCollection() {
|
||||
for array in self.tests {
|
||||
XCTAssertEqualSequences(array.compactMap({ $0 }).reversed(),
|
||||
array.compacted().reversed())
|
||||
}
|
||||
}
|
||||
|
||||
func testCollectionTraversals() {
|
||||
let validator = IndexValidator<CompactedCollection<[Int?], Int>>()
|
||||
for array in self.tests {
|
||||
validator.validate(array.compacted())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,28 +19,70 @@ final class CycleTests: XCTestCase {
|
||||
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],
|
||||
cycle.prefix(20)
|
||||
)
|
||||
}
|
||||
|
||||
func testCycleClosedRangePrefix() {
|
||||
let a = Array((0..<17).cycled().prefix(10_000))
|
||||
XCTAssertEqual(10_000, a.count)
|
||||
|
||||
}
|
||||
|
||||
func testEmptyCycle() {
|
||||
let empty = Array("".cycled())
|
||||
XCTAssert(empty.isEmpty)
|
||||
}
|
||||
|
||||
|
||||
func testCycleLazy() {
|
||||
XCTAssertLazySequence((1...4).lazy.cycled())
|
||||
}
|
||||
|
||||
func testRepeated() {
|
||||
let repeats = (1...4).cycled(times: 3)
|
||||
XCTAssertEqualSequences(
|
||||
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],
|
||||
repeats)
|
||||
|
||||
}
|
||||
|
||||
func testRepeatedClosedRange() {
|
||||
let repeats = Array((1..<5).cycled(times: 2500))
|
||||
XCTAssertEqual(10_000, repeats.count)
|
||||
}
|
||||
|
||||
func testRepeatedEmptyCollection() {
|
||||
let empty1 = Array("".cycled(times: 100))
|
||||
XCTAssert(empty1.isEmpty)
|
||||
|
||||
}
|
||||
|
||||
func testRepeatedZeroTimesCycle() {
|
||||
let empty2 = Array("Hello".cycled(times: 0))
|
||||
XCTAssert(empty2.isEmpty)
|
||||
}
|
||||
|
||||
func testCycleLazy() {
|
||||
XCTAssertLazySequence((1...4).lazy.cycled())
|
||||
|
||||
func testRepeatedLazy() {
|
||||
XCTAssertLazySequence((1...4).lazy.cycled(times: 3))
|
||||
}
|
||||
|
||||
func testRepeatedIndexMethods() {
|
||||
let cycle = (1..<5).cycled(times: 2)
|
||||
let startIndex = cycle.startIndex
|
||||
var nextIndex = cycle.index(after: startIndex)
|
||||
XCTAssertEqual(cycle.distance(from: startIndex, to: nextIndex), 1)
|
||||
|
||||
nextIndex = cycle.index(nextIndex, offsetBy: 5)
|
||||
XCTAssertEqual(cycle.distance(from: startIndex, to: nextIndex), 6)
|
||||
|
||||
nextIndex = cycle.index(nextIndex, offsetBy: 2, limitedBy: cycle.endIndex)!
|
||||
XCTAssertEqual(cycle.distance(from: startIndex, to: nextIndex), 8)
|
||||
|
||||
let outOfBounds = cycle.index(nextIndex, offsetBy: 1,
|
||||
limitedBy: cycle.endIndex)
|
||||
XCTAssertNil(outOfBounds)
|
||||
|
||||
let previousIndex = cycle.index(before: nextIndex)
|
||||
XCTAssertEqual(cycle.distance(from: startIndex, to: previousIndex), 7)
|
||||
}
|
||||
|
||||
func testRepeatedCount() {
|
||||
let cycle = (1..<5).cycled(times: 2)
|
||||
XCTAssertEqual(cycle.count, 8)
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Algorithms
|
||||
@testable import Algorithms
|
||||
|
||||
final class IntersperseTests: XCTestCase {
|
||||
func testSequence() {
|
||||
@@ -26,25 +26,21 @@ final class IntersperseTests: XCTestCase {
|
||||
func testString() {
|
||||
let interspersed = "ABCDE".interspersed(with: "-")
|
||||
XCTAssertEqualSequences(interspersed, "A-B-C-D-E")
|
||||
validateIndexTraversals(interspersed)
|
||||
}
|
||||
|
||||
func testStringEmpty() {
|
||||
let interspersed = "".interspersed(with: "-")
|
||||
XCTAssertEqualSequences(interspersed, "")
|
||||
validateIndexTraversals(interspersed)
|
||||
}
|
||||
|
||||
func testArray() {
|
||||
let interspersed = [1,2,3,4].interspersed(with: 0)
|
||||
XCTAssertEqualSequences(interspersed, [1,0,2,0,3,0,4])
|
||||
validateIndexTraversals(interspersed)
|
||||
}
|
||||
|
||||
func testArrayEmpty() {
|
||||
let interspersed = [].interspersed(with: 0)
|
||||
XCTAssertEqualSequences(interspersed, [])
|
||||
validateIndexTraversals(interspersed)
|
||||
}
|
||||
|
||||
func testCollection() {
|
||||
@@ -55,11 +51,53 @@ final class IntersperseTests: XCTestCase {
|
||||
func testBidirectionalCollection() {
|
||||
let reversed = "ABCDE".interspersed(with: "-").reversed()
|
||||
XCTAssertEqualSequences(reversed, "E-D-C-B-A")
|
||||
validateIndexTraversals(reversed)
|
||||
}
|
||||
|
||||
func testIndexTraversals() {
|
||||
let validator = IndexValidator<InterspersedSequence<String>>()
|
||||
validator.validate("".interspersed(with: "-"), expectedCount: 0)
|
||||
validator.validate("A".interspersed(with: "-"), expectedCount: 1)
|
||||
validator.validate("AB".interspersed(with: "-"), expectedCount: 3)
|
||||
validator.validate("ABCDE".interspersed(with: "-"), expectedCount: 9)
|
||||
}
|
||||
|
||||
func testIntersperseLazy() {
|
||||
XCTAssertLazySequence((1...).prefix(0).lazy.interspersed(with: 0))
|
||||
XCTAssertLazyCollection("ABCDE".lazy.interspersed(with: "-"))
|
||||
}
|
||||
|
||||
func testInterspersedMap() {
|
||||
XCTAssertEqualSequences(
|
||||
(0..<0).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }),
|
||||
[])
|
||||
|
||||
XCTAssertEqualSequences(
|
||||
(0..<1).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }),
|
||||
[0])
|
||||
|
||||
XCTAssertEqualSequences(
|
||||
(0..<5).lazy.interspersedMap({ $0 }, with: { $0 + $1 + 100 }),
|
||||
[0, 101, 1, 103, 2, 105, 3, 107, 4])
|
||||
}
|
||||
|
||||
func testInterspersedMapLazy() {
|
||||
XCTAssertLazySequence(AnySequence([]).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }))
|
||||
XCTAssertLazyCollection((0..<0).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }))
|
||||
}
|
||||
|
||||
func testInterspersedMapIndexTraversals() {
|
||||
let validator = IndexValidator<InterspersedMapSequence<Range<Int>, Int>>()
|
||||
validator.validate(
|
||||
(0..<0).lazy.interspersedMap({ $0 }, with: {_, _ in 100 }),
|
||||
expectedCount: 0)
|
||||
validator.validate(
|
||||
(0..<1).lazy.interspersedMap({ $0 }, with: {_, _ in 100 }),
|
||||
expectedCount: 1)
|
||||
validator.validate(
|
||||
(0..<2).lazy.interspersedMap({ $0 }, with: {_, _ in 100 }),
|
||||
expectedCount: 3)
|
||||
validator.validate(
|
||||
(0..<5).lazy.interspersedMap({ $0 }, with: {_, _ in 100 }),
|
||||
expectedCount: 9)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
@testable import Algorithms
|
||||
|
||||
final class JoinedTests: XCTestCase {
|
||||
let stringArrays = [
|
||||
[],
|
||||
[""],
|
||||
["", ""],
|
||||
["foo"],
|
||||
["foo", "bar"],
|
||||
["", "", "foo", "", "bar", "baz", ""],
|
||||
]
|
||||
|
||||
func testJoined() {
|
||||
let expected = ["", "", "", "foo", "foobar", "foobarbaz"]
|
||||
|
||||
for (strings, expected) in zip(stringArrays, expected) {
|
||||
// regular sequence
|
||||
XCTAssertEqualSequences(AnySequence(strings).joined(), expected)
|
||||
|
||||
// lazy sequence
|
||||
XCTAssertEqualSequences(AnySequence(strings).lazy.joined(), expected)
|
||||
|
||||
// regular collection
|
||||
XCTAssertEqualSequences(strings.joined(), expected)
|
||||
|
||||
// lazy collection
|
||||
XCTAssertEqualSequences(strings.lazy.joined() as FlattenCollection, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func testJoinedByElement() {
|
||||
let separator: Character = " "
|
||||
let expected = ["", "", " ", "foo", "foo bar", " foo bar baz "]
|
||||
|
||||
for (strings, expected) in zip(stringArrays, expected) {
|
||||
XCTAssertEqualSequences(AnySequence(strings).joined(by: separator), expected)
|
||||
XCTAssertEqualSequences(AnySequence(strings).lazy.joined(by: separator), expected)
|
||||
XCTAssertEqualSequences(strings.joined(by: separator), expected)
|
||||
XCTAssertEqualSequences(strings.lazy.joined(by: separator), expected)
|
||||
}
|
||||
}
|
||||
|
||||
func testJoinedBySequence() {
|
||||
let separator = ", "
|
||||
let expected = ["", "", ", ", "foo", "foo, bar", ", , foo, , bar, baz, "]
|
||||
|
||||
for (strings, expected) in zip(stringArrays, expected) {
|
||||
XCTAssertEqualSequences(AnySequence(strings).joined(by: separator), expected)
|
||||
XCTAssertEqualSequences(AnySequence(strings).lazy.joined(by: separator), expected)
|
||||
XCTAssertEqualSequences(strings.joined(by: separator), expected)
|
||||
XCTAssertEqualSequences(strings.lazy.joined(by: separator), expected)
|
||||
}
|
||||
}
|
||||
|
||||
func testJoinedByElementClosure() {
|
||||
let separator = { (left: String, right: String) -> Character in
|
||||
left.isEmpty || right.isEmpty ? " " : "-"
|
||||
}
|
||||
|
||||
let expected = ["", "", " ", "foo", "foo-bar", " foo bar-baz "]
|
||||
|
||||
for (strings, expected) in zip(stringArrays, expected) {
|
||||
XCTAssertEqualSequences(AnySequence(strings).joined(by: separator), expected)
|
||||
XCTAssertEqualSequences(AnySequence(strings).lazy.joined(by: separator), expected)
|
||||
XCTAssertEqualSequences(strings.joined(by: separator), expected)
|
||||
XCTAssertEqualSequences(strings.lazy.joined(by: separator), expected)
|
||||
}
|
||||
}
|
||||
|
||||
func testJoinedBySequenceClosure() {
|
||||
let separator = { (left: String, right: String) in
|
||||
"(\(left.count), \(right.count))"
|
||||
}
|
||||
|
||||
let expected = [
|
||||
"",
|
||||
"",
|
||||
"(0, 0)",
|
||||
"foo",
|
||||
"foo(3, 3)bar",
|
||||
"(0, 0)(0, 3)foo(3, 0)(0, 3)bar(3, 3)baz(3, 0)"
|
||||
]
|
||||
|
||||
for (strings, expected) in zip(stringArrays, expected) {
|
||||
XCTAssertEqualSequences(AnySequence(strings).joined(by: separator), expected)
|
||||
XCTAssertEqualSequences(AnySequence(strings).lazy.joined(by: separator), expected)
|
||||
XCTAssertEqualSequences(strings.joined(by: separator), expected)
|
||||
XCTAssertEqualSequences(strings.lazy.joined(by: separator), expected)
|
||||
}
|
||||
}
|
||||
|
||||
func testJoinedLazy() {
|
||||
XCTAssertLazySequence(AnySequence([[1], [2]]).lazy.joined())
|
||||
XCTAssertLazySequence(AnySequence([[1], [2]]).lazy.joined(by: 1))
|
||||
XCTAssertLazySequence(AnySequence([[1], [2]]).lazy.joined(by: { _, _ in 1 }))
|
||||
XCTAssertLazyCollection([[1], [2]].lazy.joined())
|
||||
XCTAssertLazyCollection([[1], [2]].lazy.joined(by: 1))
|
||||
XCTAssertLazyCollection([[1], [2]].lazy.joined(by: { _, _ in 1 }))
|
||||
}
|
||||
|
||||
func testJoinedIndexTraversals() {
|
||||
let validator = IndexValidator<FlattenCollection<[String]>>()
|
||||
|
||||
// the last test case takes too long to run
|
||||
for strings in stringArrays.dropLast() {
|
||||
validator.validate(strings.joined() as FlattenCollection)
|
||||
}
|
||||
}
|
||||
|
||||
func testJoinedByIndexTraversals() {
|
||||
let validator1 = IndexValidator<JoinedByCollection<[String], String>>()
|
||||
let validator2 = IndexValidator<JoinedByClosureCollection<[String], String>>()
|
||||
|
||||
// the last test case takes too long to run
|
||||
for (strings, separator) in product(stringArrays.dropLast(), ["", " ", ", "]) {
|
||||
validator1.validate(strings.joined(by: separator))
|
||||
validator2.validate(strings.lazy.joined(by: { _, _ in separator }))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -185,3 +185,90 @@ final class SortedPrefixTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class MinAndMaxTests: XCTestCase {
|
||||
/// Confirms that empty sequences yield no results.
|
||||
func testEmpty() {
|
||||
XCTAssertNil(EmptyCollection<Int>().minAndMax())
|
||||
}
|
||||
|
||||
/// Confirms the same element is used when there is only one.
|
||||
func testSingleElement() {
|
||||
let result = CollectionOfOne(2).minAndMax()
|
||||
XCTAssertEqual(result?.min, 2)
|
||||
XCTAssertEqual(result?.max, 2)
|
||||
}
|
||||
|
||||
/// Confirms the same value is used when all the elements have it.
|
||||
func testSingleValueMultipleElements() {
|
||||
let result = repeatElement(3.3, count: 5).minAndMax()
|
||||
XCTAssertEqual(result?.min, 3.3)
|
||||
XCTAssertEqual(result?.max, 3.3)
|
||||
|
||||
// Even count
|
||||
let result2 = repeatElement("c" as Character, count: 6).minAndMax()
|
||||
XCTAssertEqual(result2?.min, "c")
|
||||
XCTAssertEqual(result2?.max, "c")
|
||||
}
|
||||
|
||||
/// Confirms when the minimum value is constantly updated, but the maximum
|
||||
/// never is.
|
||||
func testRampDown() {
|
||||
let result = (1...5).reversed().minAndMax()
|
||||
XCTAssertEqual(result?.min, 1)
|
||||
XCTAssertEqual(result?.max, 5)
|
||||
|
||||
// Even count
|
||||
let result2 = "fedcba".minAndMax()
|
||||
XCTAssertEqual(result2?.min, "a")
|
||||
XCTAssertEqual(result2?.max, "f")
|
||||
}
|
||||
|
||||
/// Confirms when the maximum value is constantly updated, but the minimum
|
||||
/// never is.
|
||||
func testRampUp() {
|
||||
let result = (1...5).minAndMax()
|
||||
XCTAssertEqual(result?.min, 1)
|
||||
XCTAssertEqual(result?.max, 5)
|
||||
|
||||
// Even count
|
||||
let result2 = "abcdef".minAndMax()
|
||||
XCTAssertEqual(result2?.min, "a")
|
||||
XCTAssertEqual(result2?.max, "f")
|
||||
}
|
||||
|
||||
/// Confirms when the maximum and minimum change during a run.
|
||||
func testUpsAndDowns() {
|
||||
let result = [4, 3, 3, 5, 2, 0, 7, 6].minAndMax()
|
||||
XCTAssertEqual(result?.min, 0)
|
||||
XCTAssertEqual(result?.max, 7)
|
||||
|
||||
// Odd count
|
||||
let result2 = "gfabdec".minAndMax()
|
||||
XCTAssertEqual(result2?.min, "a")
|
||||
XCTAssertEqual(result2?.max, "g")
|
||||
}
|
||||
|
||||
/// Confirms that the given predicate is used to find the min/max.
|
||||
func testPredicate() {
|
||||
let result = (1...5).minAndMax(by: >)
|
||||
XCTAssertEqual(result?.min, 5)
|
||||
XCTAssertEqual(result?.max, 1)
|
||||
|
||||
// Odd count
|
||||
let result2 = "gfabdec".minAndMax(by: >)
|
||||
XCTAssertEqual(result2?.min, "g")
|
||||
XCTAssertEqual(result2?.max, "a")
|
||||
}
|
||||
|
||||
/// Confirms that the min and max are "stable" as defined for minAndMax.
|
||||
func testStability() {
|
||||
for n in 1...10 {
|
||||
let result = repeatElement(0, count: n)
|
||||
.enumerated()
|
||||
.minAndMax(by: { $0.element < $1.element })
|
||||
XCTAssertEqual(result?.min.offset, 0)
|
||||
XCTAssertEqual(result?.max.offset, n - 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -92,6 +92,26 @@ final class PartitionTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testPartitioningIndexWithEmptyInput() {
|
||||
let input: [Int] = []
|
||||
|
||||
let a = input.partitioningIndex(where: { _ in return true })
|
||||
XCTAssertEqual(a, input.startIndex)
|
||||
|
||||
let b = input.partitioningIndex(where: { _ in return false })
|
||||
XCTAssertEqual(b, input.endIndex)
|
||||
}
|
||||
|
||||
func testPartitioningIndexWithOneEmptyPartition() {
|
||||
let input: Range<Int> = (0 ..< 10)
|
||||
|
||||
let a = input.partitioningIndex(where: { $0 > 10 })
|
||||
XCTAssertEqual(a, input.endIndex)
|
||||
|
||||
let b = input.partitioningIndex(where: { $0 >= 0 })
|
||||
XCTAssertEqual(b, input.startIndex)
|
||||
}
|
||||
|
||||
func testPartitionWithSubrangeBidirectionalCollection() {
|
||||
for length in 10...20 {
|
||||
let a = Array(0..<length)
|
||||
@@ -133,4 +153,40 @@ final class PartitionTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testPartitionedWithEmptyInput() {
|
||||
let input: [Int] = []
|
||||
|
||||
let s0 = input.partitioned(by: { _ in return true })
|
||||
|
||||
XCTAssertTrue(s0.0.isEmpty)
|
||||
XCTAssertTrue(s0.1.isEmpty)
|
||||
}
|
||||
|
||||
/// Test the example given in the `partitioned(by:)` documentation
|
||||
func testPartitionedExample() throws {
|
||||
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
|
||||
let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })
|
||||
XCTAssertEqual(longNames, ["Vivien", "Marlon"])
|
||||
XCTAssertEqual(shortNames, ["Kim", "Karl"])
|
||||
}
|
||||
|
||||
func testPartitionedWithPredicate() throws {
|
||||
let s0 = ["A", "B", "C", "D"].partitioned(by: { $0 == $0.lowercased() })
|
||||
let s1 = ["a", "B", "C", "D"].partitioned(by: { $0 == $0.lowercased() })
|
||||
let s2 = ["a", "B", "c", "D"].partitioned(by: { $0 == $0.lowercased() })
|
||||
let s3 = ["a", "B", "c", "d"].partitioned(by: { $0 == $0.lowercased() })
|
||||
|
||||
XCTAssertEqual(s0.0, ["A", "B", "C", "D"])
|
||||
XCTAssertEqual(s0.1, [])
|
||||
|
||||
XCTAssertEqual(s1.0, ["B", "C", "D"])
|
||||
XCTAssertEqual(s1.1, ["a"])
|
||||
|
||||
XCTAssertEqual(s2.0, ["B", "D"])
|
||||
XCTAssertEqual(s2.1, ["a", "c"])
|
||||
|
||||
XCTAssertEqual(s3.0, ["B"])
|
||||
XCTAssertEqual(s3.1, ["a", "c", "d"])
|
||||
}
|
||||
}
|
||||
@@ -39,17 +39,18 @@ final class ProductTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testProductIndexTraversals() {
|
||||
validateIndexTraversals(
|
||||
product([1, 2, 3, 4], "abc"),
|
||||
product([1, 2, 3, 4], ""),
|
||||
product([], "abc"),
|
||||
product([], ""),
|
||||
indices: { product in
|
||||
let validator = IndexValidator<Product2Sequence<[Int], String>>(
|
||||
indicesIncludingEnd: { product in
|
||||
product.base1.indices.flatMap { i1 in
|
||||
product.base2.indices.map { i2 in
|
||||
.init(i1: i1, i2: i2)
|
||||
}
|
||||
} + [.init(i1: product.base1.endIndex, i2: product.base2.startIndex)]
|
||||
})
|
||||
|
||||
validator.validate(product([1, 2, 3, 4], "abc"), expectedCount: 4 * 3)
|
||||
validator.validate(product([1, 2, 3, 4], ""), expectedCount: 4 * 0)
|
||||
validator.validate(product([], "abc"), expectedCount: 0 * 3)
|
||||
validator.validate(product([], ""), expectedCount: 0 * 0)
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,6 @@ import XCTest
|
||||
import Algorithms
|
||||
|
||||
final class ReductionsTests: XCTestCase {
|
||||
|
||||
struct TestError: Error {}
|
||||
|
||||
// MARK: - Exclusive Reductions
|
||||
@@ -52,6 +51,13 @@ final class ReductionsTests: XCTestCase {
|
||||
XCTAssertNoThrow(try [].reductions(0) { _, _ in throw TestError() })
|
||||
XCTAssertThrowsError(try [1].reductions(0) { _, _ in throw TestError() })
|
||||
}
|
||||
|
||||
func testExclusiveIndexTraversals() {
|
||||
let validator = IndexValidator<ExclusiveReductionsSequence<Range<Int>, Int>>()
|
||||
validator.validate((0..<0).lazy.reductions(0, +), expectedCount: 1)
|
||||
validator.validate((0..<1).lazy.reductions(0, +), expectedCount: 2)
|
||||
validator.validate((0..<4).lazy.reductions(0, +), expectedCount: 5)
|
||||
}
|
||||
|
||||
// MARK: - Inclusive Reductions
|
||||
|
||||
@@ -78,4 +84,11 @@ final class ReductionsTests: XCTestCase {
|
||||
XCTAssertNoThrow(try [1].reductions { _, _ in throw TestError() })
|
||||
XCTAssertThrowsError(try [1, 1].reductions { _, _ in throw TestError() })
|
||||
}
|
||||
|
||||
func testInclusiveIndexTraversals() {
|
||||
let validator = IndexValidator<InclusiveReductionsSequence<Range<Int>>>()
|
||||
validator.validate((0..<0).lazy.reductions(+), expectedCount: 0)
|
||||
validator.validate((0..<1).lazy.reductions(+), expectedCount: 1)
|
||||
validator.validate((0..<4).lazy.reductions(+), expectedCount: 4)
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -13,10 +13,10 @@ import Algorithms
|
||||
import XCTest
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Tests for `LazySplitSequence` and `LazySplitCollection`
|
||||
// Tests for `SplitSequence` and `SplitCollection`
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
final class LazySplitTests: XCTestCase {
|
||||
final class SplitTests: XCTestCase {
|
||||
func testEmpty() {
|
||||
Validator(
|
||||
subject: [],
|
||||
@@ -64,19 +64,6 @@ final class StridingTests: XCTestCase {
|
||||
// a.index(after: a.endIndex) // Precondition failed: Advancing past end index
|
||||
}
|
||||
|
||||
func testStrideCompositionEquivalence() {
|
||||
let a = (0...10)
|
||||
XCTAssertEqualSequences(a.striding(by: 6), a.striding(by: 2).striding(by: 3))
|
||||
XCTAssertTrue(a.striding(by: 6) == a.striding(by: 2).striding(by: 3))
|
||||
XCTAssert(type(of: a.striding(by: 2).striding(by: 3)) == StrideCollection<ClosedRange<Int>>.self)
|
||||
}
|
||||
|
||||
func testEquality() {
|
||||
let a = [1, 2, 3, 4, 5].striding(by: 2)
|
||||
let b = [1, 0, 3, 0, 5].striding(by: 2)
|
||||
XCTAssertEqual(a, b)
|
||||
}
|
||||
|
||||
func testStrideLast() {
|
||||
XCTAssertEqual((1...10).striding(by: 2).last, 9) // 1, 3, 5, 7, 9
|
||||
XCTAssertEqual((1...10).striding(by: 3).last, 10) // 1, 4, 7, 10
|
||||
@@ -101,31 +88,37 @@ final class StridingTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testIndexTraversals() {
|
||||
let empty = [Int]()
|
||||
validateIndexTraversals(
|
||||
empty.striding(by: 1),
|
||||
empty.striding(by: 2)
|
||||
)
|
||||
let zero_to_one_hundered_range = 0...100
|
||||
validateIndexTraversals(
|
||||
zero_to_one_hundered_range.striding(by: 10),
|
||||
zero_to_one_hundered_range.striding(by: 11),
|
||||
zero_to_one_hundered_range.striding(by: 101)
|
||||
)
|
||||
let zero_to_one_hundered_array = Array(zero_to_one_hundered_range)
|
||||
validateIndexTraversals(
|
||||
zero_to_one_hundered_array.striding(by: 10),
|
||||
zero_to_one_hundered_array.striding(by: 11),
|
||||
zero_to_one_hundered_array.striding(by: 101)
|
||||
)
|
||||
let string = "swift rocks".map(String.init)
|
||||
validateIndexTraversals(
|
||||
string.striding(by: 1),
|
||||
string.striding(by: 2),
|
||||
string.striding(by: 10)
|
||||
)
|
||||
do {
|
||||
let empty = [Int]()
|
||||
let validator = IndexValidator<StridingCollection<[Int]>>()
|
||||
validator.validate(empty.striding(by: 1))
|
||||
validator.validate(empty.striding(by: 2))
|
||||
}
|
||||
|
||||
do {
|
||||
let range = 0...100
|
||||
let validator = IndexValidator<StridingCollection<ClosedRange<Int>>>()
|
||||
validator.validate(range.striding(by: 10))
|
||||
validator.validate(range.striding(by: 11))
|
||||
validator.validate(range.striding(by: 101))
|
||||
}
|
||||
|
||||
do {
|
||||
let array = Array(0...100)
|
||||
let validator = IndexValidator<StridingCollection<[Int]>>()
|
||||
validator.validate(array.striding(by: 10))
|
||||
validator.validate(array.striding(by: 11))
|
||||
validator.validate(array.striding(by: 101))
|
||||
}
|
||||
|
||||
do {
|
||||
let string = "swift rocks"
|
||||
let validator = IndexValidator<StridingCollection<String>>()
|
||||
validator.validate(string.striding(by: 1))
|
||||
validator.validate(string.striding(by: 2))
|
||||
validator.validate(string.striding(by: 10))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func testOffsetBy() {
|
||||
let a = (0...100).striding(by: 22)
|
||||
@@ -141,4 +134,10 @@ final class StridingTests: XCTestCase {
|
||||
let i = b.index(b.startIndex, offsetBy: 2)
|
||||
XCTAssertEqual(i, b.endIndex)
|
||||
}
|
||||
|
||||
func testLazy() {
|
||||
XCTAssertLazySequence(AnySequence(0..<100).lazy.striding(by: 3))
|
||||
XCTAssertLazySequence((0..<100).lazy.striding(by: 3))
|
||||
XCTAssertLazyCollection((0..<100).lazy.striding(by: 3))
|
||||
}
|
||||
}
|
||||
@@ -59,7 +59,7 @@ extension AnyMutableCollection: MutableCollection {
|
||||
var endIndex: Base.Index { base.endIndex }
|
||||
|
||||
func index(after i: Index) -> Index {
|
||||
return base.index(after: i)
|
||||
base.index(after: i)
|
||||
}
|
||||
|
||||
subscript(position: Base.Index) -> Base.Element {
|
||||
@@ -163,93 +163,162 @@ func XCTAssertEqualCollections<C1: Collection, C2: Collection>(
|
||||
}
|
||||
}
|
||||
|
||||
/// Tests that all index traversal methods behave as expected.
|
||||
///
|
||||
/// Verifies the correctness of the implementations of `startIndex`, `endIndex`,
|
||||
/// `indices`, `count`, `isEmpty`, `index(before:)`, `index(after:)`,
|
||||
/// `index(_:offsetBy:)`, `index(_:offsetBy:limitedBy:)`, and
|
||||
/// `distance(from:to:)` by calling them with just about all possible input
|
||||
/// combinations. When provided, the `indices` function is used to to test the
|
||||
/// collection methods against.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - collections: The collections to be validated.
|
||||
/// - indices: A closure that returns the expected indices of the given
|
||||
/// collection, including its `endIndex`, in ascending order. Only use this
|
||||
/// parameter if you are able to compute the indices of the collection
|
||||
/// independently of the `Collection` conformance, e.g. by using the
|
||||
/// contents of the collection directly.
|
||||
///
|
||||
/// - Complexity: O(*n*^3) for each collection, where *n* is the length of the
|
||||
/// collection.
|
||||
func validateIndexTraversals<C>(
|
||||
_ collections: C...,
|
||||
indices: ((C) -> [C.Index])? = nil,
|
||||
file: StaticString = #file, line: UInt = #line
|
||||
) where C: BidirectionalCollection {
|
||||
for c in collections {
|
||||
let indicesIncludingEnd = indices?(c) ?? (c.indices + [c.endIndex])
|
||||
struct IndexValidator<C: Collection> {
|
||||
let testRandomAccess = true
|
||||
let indicesIncludingEnd: (C) -> [C.Index]
|
||||
|
||||
/// Creates a new instance of an index validator that can verify that indices
|
||||
/// of a collection behave correctly and consistently.
|
||||
///
|
||||
/// Usage:
|
||||
///
|
||||
/// let validator = IndexValidator<ReversedCollection<String>>()
|
||||
/// validator.validate("abc".reversed())
|
||||
/// validator.validate("xyz".reversed(), expectedCount: 3)
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - testRandomAccess: If `true`, also tests the correctness of the methods
|
||||
/// `index(_:offsetBy:)`, `index(_:offsetBy:limitedBy:)`, and
|
||||
/// `distance(from:to:)`. Only useful if the collection overrides these
|
||||
/// methods. Defaults to `true`.
|
||||
/// - indicesIncludingEnd: A closure that returns the expected indices of
|
||||
/// the given collection, including its `endIndex`, in ascending order.
|
||||
/// Only use this parameter if you are able to compute the indices of the
|
||||
/// collection independently of the `Collection` conformance, e.g. by
|
||||
/// using the contents of the collection directly.
|
||||
init(
|
||||
testRandomAccess: Bool = true,
|
||||
indicesIncludingEnd: @escaping (C) -> [C.Index] = { $0.indices + [$0.endIndex] }
|
||||
) {
|
||||
self.indicesIncludingEnd = indicesIncludingEnd
|
||||
}
|
||||
}
|
||||
|
||||
extension IndexValidator {
|
||||
fileprivate struct Validator {
|
||||
let collection: C
|
||||
let count: Int
|
||||
let indicesIncludingEnd: [C.Index]
|
||||
let file: StaticString
|
||||
let line: UInt
|
||||
}
|
||||
|
||||
/// Verifies that all index traversal methods behave as expected.
|
||||
///
|
||||
/// Verifies the correctness of the implementations of `startIndex`,
|
||||
/// `endIndex`, `indices`, `count`, `isEmpty`, `index(before:)`,
|
||||
/// `index(after:)`, `index(_:offsetBy:)`, `index(_:offsetBy:limitedBy:)`, and
|
||||
/// `distance(from:to:)` by calling them with just about all possible input
|
||||
/// combinations.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - collection: The collection to be validated.
|
||||
/// - expectedCount:
|
||||
///
|
||||
/// - Complexity: O(*n*^3) where *n* is the length of the collection if the
|
||||
/// collection conforms to `RandomAccesCollection`, otherwise O(*n*^4).
|
||||
func validate(
|
||||
_ collection: C,
|
||||
expectedCount: Int? = nil,
|
||||
file: StaticString = #file, line: UInt = #line
|
||||
) {
|
||||
let indicesIncludingEnd = self.indicesIncludingEnd(collection)
|
||||
let count = indicesIncludingEnd.count - 1
|
||||
|
||||
let validator = Validator(
|
||||
collection: collection,
|
||||
count: count,
|
||||
indicesIncludingEnd: indicesIncludingEnd,
|
||||
file: file, line: line)
|
||||
|
||||
validator.validateForward(
|
||||
testRandomAccess: testRandomAccess,
|
||||
expectedCount: expectedCount)
|
||||
}
|
||||
}
|
||||
|
||||
extension IndexValidator where C: BidirectionalCollection {
|
||||
func validate(
|
||||
_ collection: C, expectedCount: Int? = nil,
|
||||
file: StaticString = #file, line: UInt = #line
|
||||
) {
|
||||
let indicesIncludingEnd = self.indicesIncludingEnd(collection)
|
||||
let count = indicesIncludingEnd.count - 1
|
||||
|
||||
let validator = Validator(
|
||||
collection: collection,
|
||||
count: count,
|
||||
indicesIncludingEnd: indicesIncludingEnd,
|
||||
file: file, line: line)
|
||||
|
||||
validator.validateForward(
|
||||
testRandomAccess: testRandomAccess,
|
||||
expectedCount: expectedCount)
|
||||
validator.validateBackward(testRandomAccess: testRandomAccess)
|
||||
}
|
||||
}
|
||||
|
||||
extension IndexValidator.Validator {
|
||||
func validateForward(testRandomAccess: Bool, expectedCount: Int?) {
|
||||
if let expectedCount = expectedCount {
|
||||
XCTAssertEqual(
|
||||
expectedCount, count, "Count mismatch", file: file, line: line)
|
||||
}
|
||||
|
||||
XCTAssertEqual(
|
||||
c.count, count,
|
||||
collection.count, count,
|
||||
"Count mismatch",
|
||||
file: file, line: line)
|
||||
XCTAssertEqual(
|
||||
c.isEmpty, count == 0,
|
||||
collection.isEmpty, count == 0,
|
||||
"Emptiness mismatch",
|
||||
file: file, line: line)
|
||||
XCTAssertEqual(
|
||||
c.startIndex, indicesIncludingEnd.first,
|
||||
collection.startIndex, indicesIncludingEnd.first,
|
||||
"`startIndex` does not equal the first index",
|
||||
file: file, line: line)
|
||||
XCTAssertEqual(
|
||||
c.endIndex, indicesIncludingEnd.last,
|
||||
collection.endIndex, indicesIncludingEnd.last,
|
||||
"`endIndex` does not equal the last index",
|
||||
file: file, line: line)
|
||||
|
||||
// `index(after:)`
|
||||
do {
|
||||
var index = c.startIndex
|
||||
|
||||
for (offset, expected) in indicesIncludingEnd.enumerated().dropFirst() {
|
||||
c.formIndex(after: &index)
|
||||
XCTAssertEqual(
|
||||
index, expected,
|
||||
"""
|
||||
`startIndex` incremented \(offset) times does not equal index at \
|
||||
offset \(offset)
|
||||
""",
|
||||
file: file, line: line)
|
||||
}
|
||||
}
|
||||
validateIndexAfter()
|
||||
validateIndices()
|
||||
validateIndexComparisons()
|
||||
|
||||
// `index(before:)`
|
||||
do {
|
||||
var index = c.endIndex
|
||||
|
||||
for (offset, expected) in indicesIncludingEnd.enumerated().dropLast().reversed() {
|
||||
c.formIndex(before: &index)
|
||||
XCTAssertEqual(
|
||||
index, expected,
|
||||
"""
|
||||
`endIndex` decremented \(count - offset) times does not equal index \
|
||||
at offset \(offset)
|
||||
""",
|
||||
file: file, line: line)
|
||||
}
|
||||
if testRandomAccess {
|
||||
validateDistanceFromTo()
|
||||
validateIndexOffsetBy()
|
||||
validateIndexOffsetByLimitedBy()
|
||||
}
|
||||
}
|
||||
|
||||
func validateIndexAfter() {
|
||||
var index = collection.startIndex
|
||||
|
||||
// `indices`
|
||||
XCTAssertEqual(c.indices.count, count)
|
||||
for (offset, index) in c.indices.enumerated() {
|
||||
for (offset, expected) in indicesIncludingEnd.enumerated().dropFirst() {
|
||||
collection.formIndex(after: &index)
|
||||
XCTAssertEqual(
|
||||
index, expected,
|
||||
"""
|
||||
`startIndex` incremented \(offset) times does not equal index at \
|
||||
offset \(offset)
|
||||
""",
|
||||
file: file, line: line)
|
||||
}
|
||||
}
|
||||
|
||||
func validateIndices() {
|
||||
XCTAssertEqual(collection.indices.count, count)
|
||||
for (offset, index) in collection.indices.enumerated() {
|
||||
XCTAssertEqual(
|
||||
index, indicesIncludingEnd[offset],
|
||||
"Index mismatch at offset \(offset) in `indices`",
|
||||
file: file, line: line)
|
||||
}
|
||||
|
||||
// index comparison
|
||||
}
|
||||
|
||||
func validateIndexComparisons() {
|
||||
for (offsetA, a) in indicesIncludingEnd.enumerated() {
|
||||
XCTAssertEqual(
|
||||
a, a,
|
||||
@@ -273,21 +342,14 @@ func validateIndexTraversals<C>(
|
||||
file: file, line: line)
|
||||
}
|
||||
}
|
||||
|
||||
// `index(_:offsetBy:)` and `distance(from:to:)`
|
||||
}
|
||||
|
||||
func validateDistanceFromTo() {
|
||||
for (startOffset, start) in indicesIncludingEnd.enumerated() {
|
||||
for (endOffset, end) in indicesIncludingEnd.enumerated() {
|
||||
for (endOffset, end) in indicesIncludingEnd.enumerated().dropFirst(startOffset) {
|
||||
let distance = endOffset - startOffset
|
||||
|
||||
XCTAssertEqual(
|
||||
c.index(start, offsetBy: distance), end,
|
||||
"""
|
||||
Index at offset \(startOffset) offset by \(distance) does not equal \
|
||||
index at offset \(endOffset)
|
||||
""",
|
||||
file: file, line: line)
|
||||
XCTAssertEqual(
|
||||
c.distance(from: start, to: end), distance,
|
||||
collection.distance(from: start, to: end), distance,
|
||||
"""
|
||||
Distance from index at offset \(startOffset) to index at offset \
|
||||
\(endOffset) does not equal \(distance)
|
||||
@@ -295,18 +357,34 @@ func validateIndexTraversals<C>(
|
||||
file: file, line: line)
|
||||
}
|
||||
}
|
||||
|
||||
// `index(_:offsetBy:limitedBy:)`
|
||||
}
|
||||
|
||||
func validateIndexOffsetBy() {
|
||||
for (startOffset, start) in indicesIncludingEnd.enumerated() {
|
||||
for (endOffset, end) in indicesIncludingEnd.enumerated().dropFirst(startOffset) {
|
||||
let distance = endOffset - startOffset
|
||||
XCTAssertEqual(
|
||||
collection.index(start, offsetBy: distance), end,
|
||||
"""
|
||||
Index at offset \(startOffset) offset by \(distance) does not \
|
||||
equal index at offset \(endOffset)
|
||||
""",
|
||||
file: file, line: line)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func validateIndexOffsetByLimitedBy() {
|
||||
for (startOffset, start) in indicesIncludingEnd.enumerated() {
|
||||
for (limitOffset, limit) in indicesIncludingEnd.enumerated() {
|
||||
// verifies that the target index corresponding to each offset in
|
||||
// `range` can or cannot be reached from `start` using
|
||||
// `chain.index(start, offsetBy: _, limitedBy: limit)`, depending on the
|
||||
// value of `pastLimit`
|
||||
// `chain.index(start, offsetBy: _, limitedBy: limit)`, depending on
|
||||
// the value of `pastLimit`
|
||||
func checkTargetRange(_ range: ClosedRange<Int>, pastLimit: Bool) {
|
||||
for targetOffset in range {
|
||||
let distance = targetOffset - startOffset
|
||||
let end = c.index(start, offsetBy: distance, limitedBy: limit)
|
||||
let end = collection.index(start, offsetBy: distance, limitedBy: limit)
|
||||
|
||||
if pastLimit {
|
||||
XCTAssertNil(
|
||||
@@ -329,7 +407,6 @@ func validateIndexTraversals<C>(
|
||||
}
|
||||
}
|
||||
|
||||
// forward offsets
|
||||
if limit >= start {
|
||||
// the limit has an effect
|
||||
checkTargetRange(startOffset...limitOffset, pastLimit: false)
|
||||
@@ -338,8 +415,100 @@ func validateIndexTraversals<C>(
|
||||
// the limit has no effect
|
||||
checkTargetRange(startOffset...count, pastLimit: false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension IndexValidator.Validator where C: BidirectionalCollection {
|
||||
func validateBackward(testRandomAccess: Bool) {
|
||||
validateIndexBefore()
|
||||
|
||||
if testRandomAccess {
|
||||
validateDistanceFromTo()
|
||||
validateIndexOffsetBy()
|
||||
validateIndexOffsetByLimitedBy()
|
||||
}
|
||||
}
|
||||
|
||||
func validateIndexBefore() {
|
||||
var index = collection.endIndex
|
||||
|
||||
for (offset, expected) in indicesIncludingEnd.enumerated().dropLast().reversed() {
|
||||
collection.formIndex(before: &index)
|
||||
XCTAssertEqual(
|
||||
index, expected,
|
||||
"""
|
||||
`endIndex` decremented \(count - offset) times does not equal index \
|
||||
at offset \(offset)
|
||||
""",
|
||||
file: file, line: line)
|
||||
}
|
||||
}
|
||||
|
||||
func validateDistanceFromTo() {
|
||||
for (startOffset, start) in indicesIncludingEnd.enumerated() {
|
||||
for (endOffset, end) in indicesIncludingEnd.enumerated().prefix(startOffset) {
|
||||
let distance = endOffset - startOffset
|
||||
XCTAssertEqual(
|
||||
collection.distance(from: start, to: end), distance,
|
||||
"""
|
||||
Distance from index at offset \(startOffset) to index at offset \
|
||||
\(endOffset) does not equal \(distance)
|
||||
""",
|
||||
file: file, line: line)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func validateIndexOffsetBy() {
|
||||
for (startOffset, start) in indicesIncludingEnd.enumerated() {
|
||||
for (endOffset, end) in indicesIncludingEnd.enumerated().prefix(startOffset) {
|
||||
let distance = endOffset - startOffset
|
||||
XCTAssertEqual(
|
||||
collection.index(start, offsetBy: distance), end,
|
||||
"""
|
||||
Index at offset \(startOffset) offset by \(distance) does not \
|
||||
equal index at offset \(endOffset)
|
||||
""",
|
||||
file: file, line: line)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func validateIndexOffsetByLimitedBy() {
|
||||
for (startOffset, start) in indicesIncludingEnd.enumerated() {
|
||||
for (limitOffset, limit) in indicesIncludingEnd.enumerated() {
|
||||
// verifies that the target index corresponding to each offset in
|
||||
// `range` can or cannot be reached from `start` using
|
||||
// `chain.index(start, offsetBy: _, limitedBy: limit)`, depending on
|
||||
// the value of `pastLimit`
|
||||
func checkTargetRange(_ range: ClosedRange<Int>, pastLimit: Bool) {
|
||||
for targetOffset in range {
|
||||
let distance = targetOffset - startOffset
|
||||
let end = collection.index(start, offsetBy: distance, limitedBy: limit)
|
||||
|
||||
if pastLimit {
|
||||
XCTAssertNil(
|
||||
end,
|
||||
"""
|
||||
Index at offset \(startOffset) offset by \(distance) limited \
|
||||
by index at offset \(limitOffset) does not equal `nil`
|
||||
""",
|
||||
file: file, line: line)
|
||||
} else {
|
||||
XCTAssertEqual(
|
||||
end, indicesIncludingEnd[targetOffset],
|
||||
"""
|
||||
Index at offset \(startOffset) offset by \(distance) limited \
|
||||
by index at offset \(limitOffset) does not equal index at \
|
||||
offset \(targetOffset)
|
||||
""",
|
||||
file: file, line: line)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// backward offsets
|
||||
if limit <= start {
|
||||
// the limit has an effect
|
||||
checkTargetRange(limitOffset...startOffset, pastLimit: false)
|
||||
|
||||
@@ -13,12 +13,12 @@ import Algorithms
|
||||
import XCTest
|
||||
|
||||
final class TrimTests: XCTestCase {
|
||||
|
||||
|
||||
func testEmpty() {
|
||||
let results_empty = ([] as [Int]).trimming { $0.isMultiple(of: 2) }
|
||||
XCTAssertEqual(results_empty, [])
|
||||
}
|
||||
|
||||
|
||||
func testNoMatch() {
|
||||
// No match (nothing trimmed).
|
||||
let results_nomatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming {
|
||||
@@ -26,34 +26,83 @@ final class TrimTests: XCTestCase {
|
||||
}
|
||||
XCTAssertEqual(results_nomatch, [1, 3, 5, 7, 9, 11, 13, 15])
|
||||
}
|
||||
|
||||
|
||||
func testNoTailMatch() {
|
||||
// No tail match (only trim head).
|
||||
let results_notailmatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming { $0 < 10 }
|
||||
XCTAssertEqual(results_notailmatch, [11, 13, 15])
|
||||
}
|
||||
|
||||
|
||||
func testNoHeadMatch() {
|
||||
// No head match (only trim tail).
|
||||
let results_noheadmatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming { $0 > 10 }
|
||||
XCTAssertEqual(results_noheadmatch, [1, 3, 5, 7, 9])
|
||||
}
|
||||
|
||||
|
||||
func testBothEndsMatch() {
|
||||
// Both ends match, some string of >1 elements do not (return that string).
|
||||
let results = [2, 10, 11, 15, 20, 21, 100].trimming { $0.isMultiple(of: 2) }
|
||||
XCTAssertEqual(results, [11, 15, 20, 21])
|
||||
}
|
||||
|
||||
|
||||
func testEverythingMatches() {
|
||||
// Everything matches (trim everything).
|
||||
let results_allmatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming { _ in true }
|
||||
XCTAssertEqual(results_allmatch, [])
|
||||
}
|
||||
|
||||
|
||||
func testEverythingButOneMatches() {
|
||||
// Both ends match, one element does not (trim all except that element).
|
||||
let results_one = [2, 10, 12, 15, 20, 100].trimming { $0.isMultiple(of: 2) }
|
||||
XCTAssertEqual(results_one, [15])
|
||||
}
|
||||
|
||||
func testTrimmingPrefix() {
|
||||
let results = [2, 10, 12, 15, 20, 100].trimmingPrefix { $0.isMultiple(of: 2) }
|
||||
XCTAssertEqual(results, [15, 20, 100])
|
||||
}
|
||||
|
||||
func testTrimmingSuffix() {
|
||||
let results = [2, 10, 12, 15, 20, 100].trimmingSuffix { $0.isMultiple(of: 2) }
|
||||
XCTAssertEqual(results, [2, 10, 12, 15])
|
||||
}
|
||||
|
||||
// Self == Self.Subsequence
|
||||
func testTrimNoAmbiguity() {
|
||||
var values = [2, 10, 12, 15, 20, 100] as ArraySlice
|
||||
values.trim { $0.isMultiple(of: 2) }
|
||||
XCTAssertEqual(values, [15])
|
||||
}
|
||||
|
||||
// Self == Self.Subsequence
|
||||
func testTrimPrefixNoAmbiguity() {
|
||||
var values = [2, 10, 12, 15, 20, 100] as ArraySlice
|
||||
values.trimPrefix { $0.isMultiple(of: 2) }
|
||||
XCTAssertEqual(values, [15, 20, 100])
|
||||
}
|
||||
|
||||
// Self == Self.Subsequence
|
||||
func testTrimSuffixNoAmbiguity() {
|
||||
var values = [2, 10, 12, 15, 20, 100] as ArraySlice
|
||||
values.trimSuffix { $0.isMultiple(of: 2) }
|
||||
XCTAssertEqual(values, [2, 10, 12, 15])
|
||||
}
|
||||
|
||||
func testTrimRangeReplaceable() {
|
||||
var values = [2, 10, 12, 15, 20, 100]
|
||||
values.trim { $0.isMultiple(of: 2) }
|
||||
XCTAssertEqual(values, [15])
|
||||
}
|
||||
|
||||
func testTrimPrefixRangeReplaceable() {
|
||||
var values = [2, 10, 12, 15, 20, 100]
|
||||
values.trimPrefix { $0.isMultiple(of: 2) }
|
||||
XCTAssertEqual(values, [15, 20, 100])
|
||||
}
|
||||
|
||||
func testTrimSuffixRangeReplaceable() {
|
||||
var values = [2, 10, 12, 15, 20, 100]
|
||||
values.trimSuffix { $0.isMultiple(of: 2) }
|
||||
XCTAssertEqual(values, [2, 10, 12, 15])
|
||||
}
|
||||
}
|
||||
@@ -17,10 +17,13 @@ final class UniqueTests: XCTestCase {
|
||||
let a = repeatElement(1...10, count: 15).joined().shuffled()
|
||||
let b = a.uniqued()
|
||||
XCTAssertEqual(b.sorted(), Set(a).sorted())
|
||||
XCTAssertEqual(10, b.count)
|
||||
XCTAssertEqual(10, Array(b).count)
|
||||
|
||||
let c: [Int] = []
|
||||
XCTAssertEqual(c.uniqued(), [])
|
||||
XCTAssertEqualSequences(c.uniqued(), [])
|
||||
|
||||
let d = Array(repeating: 1, count: 10)
|
||||
XCTAssertEqualSequences(d.uniqued(), [1])
|
||||
}
|
||||
|
||||
func testUniqueOn() {
|
||||
@@ -30,5 +33,21 @@ final class UniqueTests: XCTestCase {
|
||||
|
||||
let c: [Int] = []
|
||||
XCTAssertEqual(c.uniqued(on: { $0.bitWidth }), [])
|
||||
|
||||
let d = Array(repeating: "Andromeda", count: 10)
|
||||
XCTAssertEqualSequences(d.uniqued(on: { $0.first }), ["Andromeda"])
|
||||
}
|
||||
|
||||
func testLazyUniqueOn() {
|
||||
let a = ["Albemarle", "Abeforth", "Astrology", "Brandywine", "Beatrice", "Axiom"]
|
||||
let b = a.lazy.uniqued(on: { $0.first })
|
||||
XCTAssertEqualSequences(b, ["Albemarle", "Brandywine"])
|
||||
XCTAssertLazySequence(b)
|
||||
|
||||
let c: [Int] = []
|
||||
XCTAssertEqualSequences(c.lazy.uniqued(on: { $0.bitWidth }), [])
|
||||
|
||||
let d = Array(repeating: "Andromeda", count: 10)
|
||||
XCTAssertEqualSequences(d.lazy.uniqued(on: { $0.first }), ["Andromeda"])
|
||||
}
|
||||
}
|
||||
@@ -12,8 +12,7 @@
|
||||
import XCTest
|
||||
@testable import Algorithms
|
||||
|
||||
final class windowsTests: XCTestCase {
|
||||
|
||||
final class WindowsTests: XCTestCase {
|
||||
func testWindowsOfString() {
|
||||
let s = "swift"
|
||||
let w = s.windows(ofCount: 2)
|
||||
@@ -87,22 +86,23 @@ final class windowsTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testWindowsIndexTraversals() {
|
||||
validateIndexTraversals(
|
||||
"".windows(ofCount: 1),
|
||||
"a".windows(ofCount: 1),
|
||||
"ab".windows(ofCount: 1),
|
||||
"abc".windows(ofCount: 1),
|
||||
"".windows(ofCount: 3),
|
||||
"a".windows(ofCount: 3),
|
||||
"abc".windows(ofCount: 3),
|
||||
"abcdefgh".windows(ofCount: 3),
|
||||
indices: { windows in
|
||||
let validator = IndexValidator<WindowsOfCountCollection<String>>(
|
||||
indicesIncludingEnd: { windows in
|
||||
let endIndex = windows.base.endIndex
|
||||
let indices = windows.base.indices + [endIndex]
|
||||
return zip(indices, indices.dropFirst(windows.size))
|
||||
return zip(indices, indices.dropFirst(windows.windowSize))
|
||||
.map { .init(lowerBound: $0, upperBound: $1) }
|
||||
+ [.init(lowerBound: endIndex, upperBound: endIndex)]
|
||||
+ [.init(lowerBound: endIndex, upperBound: endIndex)]
|
||||
})
|
||||
|
||||
validator.validate("".windows(ofCount: 1), expectedCount: 0)
|
||||
validator.validate("a".windows(ofCount: 1), expectedCount: 1)
|
||||
validator.validate("ab".windows(ofCount: 1), expectedCount: 2)
|
||||
validator.validate("abc".windows(ofCount: 1), expectedCount: 3)
|
||||
validator.validate("".windows(ofCount: 3), expectedCount: 0)
|
||||
validator.validate("a".windows(ofCount: 3), expectedCount: 0)
|
||||
validator.validate("abc".windows(ofCount: 3), expectedCount: 1)
|
||||
validator.validate("abcdefgh".windows(ofCount: 3), expectedCount: 6)
|
||||
}
|
||||
|
||||
func testWindowsLazy() {
|
||||
|
||||
Reference in new issue
Block a user