mirror of
https://github.com/apple/swift-algorithms
synced 2026-11-22 04:10:39 +00:00
Compare commits
1
Commits
0.2.1
..
nate/bench
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b333caf0a5 |
No files matched your search
@@ -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](../blob/main/CONTRIBUTING.md)
|
||||
- [ ] I've read the [Contribution Guidelines](../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](../../blob/main/CONTRIBUTING.md)
|
||||
- [ ] I've read the [Contribution Guidelines](../../CONTRIBUTING.md)
|
||||
- [ ] I've updated the documentation if necessary
|
||||
+3
-141
@@ -8,124 +8,14 @@ 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.1.0")` as the requirement.
|
||||
`.upToNextMinor(from: "0.0.1")` as the requirement.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
*No new changes.*
|
||||
*No changes yet.*
|
||||
|
||||
---
|
||||
|
||||
## [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
|
||||
@@ -206,12 +96,7 @@ 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.2.1...HEAD
|
||||
[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
|
||||
[Unreleased]: https://github.com/apple/swift-algorithms/compare/0.0.3...HEAD
|
||||
[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
|
||||
@@ -222,54 +107,32 @@ 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
|
||||
[#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
|
||||
|
||||
<!-- 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
|
||||
[egorzhdan]: https://github.com/apple/swift-algorithms/commits?author=egorzhdan
|
||||
[fedeci]: https://github.com/apple/swift-algorithms/commits?author=fedeci
|
||||
[hashemi]: https://github.com/apple/swift-algorithms/commits?author=hashemi
|
||||
[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
|
||||
[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
|
||||
@@ -277,4 +140,3 @@ 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
|
||||
@@ -1,52 +0,0 @@
|
||||
# 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.
|
||||
|
||||
[naming]: https://forums.swift.org/t/naming-of-chained-with/40999/
|
||||
|
||||
### 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`.
|
||||
+15
-17
@@ -22,20 +22,18 @@ let chunks = numbers.chunked(by: { $0 <= $1 })
|
||||
|
||||
The `chunk(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!)
|
||||
// [("D", ["David"]), ("K", ["Kyle", "Karoy"]), ("N", ["Nate"])]
|
||||
// [["David"], ["Kyle", "Karoy"], ["Nate"]]
|
||||
```
|
||||
|
||||
The `chunks(ofCount:)` method takes a `count` parameter (greater than zero)
|
||||
and separates the collection into chunks of this given count.
|
||||
If the `count` parameter is evenly divided by the count of the base `Collection`,
|
||||
all the chunks will have a count equal to the parameter.
|
||||
Otherwise, the last chunk will contain the remaining elements.
|
||||
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.
|
||||
|
||||
```swift
|
||||
let names = ["David", "Kyle", "Karoy", "Nate"]
|
||||
@@ -46,17 +44,17 @@ let remaining = names.chunks(ofCount: 3)
|
||||
// equivalent to [["David", "Kyle", "Karoy"], ["Nate"]]
|
||||
```
|
||||
|
||||
The `chunks(ofCount:)` is the subject of an [existing SE proposal][proposal].
|
||||
|
||||
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 recreates the original collection.
|
||||
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.
|
||||
|
||||
```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
|
||||
@@ -72,21 +70,21 @@ extension Collection {
|
||||
|
||||
public func chunked<Subject: Equatable>(
|
||||
on projection: (Element) -> Subject
|
||||
) -> [(Subject, SubSequence)]
|
||||
) -> [SubSequence]
|
||||
}
|
||||
|
||||
extension LazyCollectionProtocol {
|
||||
public func chunked(
|
||||
by belongInSameGroup: @escaping (Element, Element) -> Bool
|
||||
) -> ChunkedBy<Elements, Element>
|
||||
) -> LazyChunked<Elements>
|
||||
|
||||
public func chunked<Subject: Equatable>(
|
||||
on projection: @escaping (Element) -> Subject
|
||||
) -> ChunkedOn<Elements, Subject>
|
||||
) -> LazyChunked<Elements>
|
||||
}
|
||||
```
|
||||
|
||||
The `ChunkedBy` and `ChunkedOn` types are bidirectional when the wrapped collection is
|
||||
The `LazyChunked` type is bidirectional when the wrapped collection is
|
||||
bidirectional.
|
||||
|
||||
### Complexity
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
# 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` and
|
||||
`LazyCollectionProtocol` 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.
|
||||
+8
-9
@@ -16,9 +16,9 @@ for x in (1...3).cycled(times: 3) {
|
||||
// Prints 1 through 3 three 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()`.
|
||||
`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.
|
||||
|
||||
## Detailed Design
|
||||
|
||||
@@ -28,7 +28,7 @@ Two new methods are added to collections:
|
||||
extension Collection {
|
||||
func cycled() -> Cycle<Self>
|
||||
|
||||
func cycled(times: Int) -> FiniteCycle<Self>
|
||||
func cycled(times: Int) -> FlattenSequence<Repeated<Self>>
|
||||
}
|
||||
```
|
||||
|
||||
@@ -36,10 +36,9 @@ 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 `FiniteCycle` type always has `Collection` conformance, with
|
||||
`BidirectionalCollection` conformance
|
||||
when called on a bidirectional collection. `FiniteCycle` also
|
||||
conforms to `LazyCollectionProtocol` 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.
|
||||
|
||||
### Complexity
|
||||
|
||||
@@ -62,4 +61,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.
|
||||
+18
-60
@@ -2,48 +2,23 @@
|
||||
|
||||
[[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)]
|
||||
|
||||
Returns the first non-`nil` result obtained from applying the given
|
||||
transformation to the elements of the sequence.
|
||||
|
||||
Retrieves the first `.some` encountered while applying the given transform.
|
||||
|
||||
This operation is available through the `firstNonNil(_:)` method on any sequence.
|
||||
|
||||
```swift
|
||||
let strings = ["three", "3.14", "-5", "2"]
|
||||
if let firstInt = strings.firstNonNil({ Int($0) }) {
|
||||
print(firstInt)
|
||||
// -5
|
||||
}
|
||||
let value = ["A", "B", "10"].firstNonNil { Int($0) }
|
||||
// value == .some(10)
|
||||
//
|
||||
let noValue = ["A", "B", "C"].firstNonNil { Int($0) }
|
||||
// noValue == .none
|
||||
```
|
||||
|
||||
Like `first(where:)`, this method stops iterating the sequence once a match is
|
||||
found. Use `firstNonNil(_:)` to avoid having to apply a transformation twice:
|
||||
|
||||
```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 {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
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.
|
||||
|
||||
## Detailed Design
|
||||
|
||||
@@ -52,34 +27,17 @@ 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
|
||||
|
||||
Some alternative names were considered:
|
||||
|
||||
* `compactMapFirst(_:)`
|
||||
* `first(mapping:)`
|
||||
* `firstSome(_:)`
|
||||
* `firstMap(_:)`
|
||||
This method’s name was selected for its comprehensibility.
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
**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.
|
||||
**Scala**: Scala provides a `collectFirst` function that finds the first element
|
||||
in a collection for which a partial function is defined.
|
||||
@@ -1,102 +0,0 @@
|
||||
# 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
|
||||
`LazySequenceProtocol` and `LazyCollectionProtocol` 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 LazyCollectionProtocol where 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 `LazyCollectionProtocol` and `BidirectionalCollection` when the base
|
||||
collection conforms.
|
||||
+3
-30
@@ -1,4 +1,4 @@
|
||||
# Minima and/or Maxima
|
||||
# Min/Max with Count
|
||||
|
||||
[[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)]
|
||||
@@ -13,17 +13,6 @@ 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:
|
||||
@@ -42,16 +31,6 @@ extension Collection {
|
||||
}
|
||||
```
|
||||
|
||||
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
|
||||
@@ -60,26 +39,20 @@ 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 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)`.
|
||||
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)`.
|
||||
|
||||
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. It also defines a `minmax_element` function that scans a range for its minimal and maximal elements.
|
||||
**C++:** The `<algorithm>` library defines a `partial_sort` function where the entire array is returned using a partial heap sort.
|
||||
|
||||
**Python:** Defines a `heapq` priority queue that can be used to manually achieve the same result.
|
||||
|
||||
+13
-35
@@ -3,7 +3,7 @@
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Permutations.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/PermutationsTests.swift)]
|
||||
|
||||
Methods that compute permutations of a collection’s elements, or of a subset of
|
||||
A type that computes permutations of a collection’s elements, or of a subset of
|
||||
those elements.
|
||||
|
||||
The `permutations(ofCount:)` method, when called without the `ofCount`
|
||||
@@ -60,18 +60,7 @@ for perm in numbers2.permutations() {
|
||||
// [10, 10, 20]
|
||||
```
|
||||
|
||||
To generate only unique permutations, use the `uniquePermutations(ofCount:)` method:
|
||||
|
||||
```swift
|
||||
for perm in numbers2.uniquePermutations() {
|
||||
print(perm)
|
||||
}
|
||||
// [20, 10, 10]
|
||||
// [10, 20, 10]
|
||||
// [10, 10, 20]
|
||||
```
|
||||
|
||||
Given a range, the methods return a sequence of all the different permutations of the given sizes of a collection’s elements in increasing order of size.
|
||||
Given a range, the `permutations(ofCount:)` method returns a sequence of all the different permutations of the given sizes of a collection’s elements in increasing order of size.
|
||||
|
||||
```swift
|
||||
let numbers = [10, 20, 30]
|
||||
@@ -98,29 +87,21 @@ 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:)` method is declared as a `Collection` extension,
|
||||
and returns a `Permutations` type:
|
||||
|
||||
```swift
|
||||
extension Collection {
|
||||
public func permutations(ofCount k: Int? = nil) -> Permutations<Self>
|
||||
public func permutations<R>(ofCount kRange: R) -> Permutations<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>
|
||||
where R: RangeExpression, R.Bound == Int
|
||||
}
|
||||
```
|
||||
|
||||
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
|
||||
Since the `Permutations` type needs to store an array of the collection’s
|
||||
indices and mutate the array to generate each permutation, `Permutations` 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. The `Permutations` type
|
||||
conforms to `LazySequenceProtocol` when its base type conforms.
|
||||
array at every index advancement. `Combinations` does conform to
|
||||
`LazySequenceProtocol` when the base type conforms.
|
||||
|
||||
### Complexity
|
||||
|
||||
@@ -128,10 +109,6 @@ 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.
|
||||
|
||||
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
|
||||
|
||||
See the ["Naming" section for `combinations(ofCount:)`](Combinations.md#naming) for detail.
|
||||
@@ -140,8 +117,9 @@ See the ["Naming" section for `combinations(ofCount:)`](Combinations.md#naming)
|
||||
|
||||
**C++:** The `<algorithm>` library defines a `next_permutation` function that
|
||||
advances an array of comparable values through their lexicographic orderings.
|
||||
This function is very similar to the `uniquePermutations(ofCount:)` method.
|
||||
This function is tricky to use and understand, so while it’s included in
|
||||
`swift-algorithms` as an implementation detail of the `Permutations` type, it
|
||||
isn’t public.
|
||||
|
||||
**Rust/Ruby/Python:** Rust, Ruby, and Python all define functions with
|
||||
essentially the same semantics as the `permutations(ofCount:)` method
|
||||
described here.
|
||||
essentially the same semantics as the method described here.
|
||||
@@ -1,134 +0,0 @@
|
||||
# Reductions
|
||||
|
||||
[[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 all the intermediate results of reducing a sequence's elements using a closure.
|
||||
|
||||
```swift
|
||||
let exclusiveRunningTotal = (1...5).reductions(0, +)
|
||||
print(exclusiveRunningTotal)
|
||||
// prints [0, 1, 3, 6, 10, 15]
|
||||
|
||||
let intoRunningTotal = (1...5).reductions(into: 0, +=)
|
||||
print(intoRunningTotal)
|
||||
// prints [0, 1, 3, 6, 10, 15]
|
||||
|
||||
let inclusiveRunningTotal = (1...5).reductions(+)
|
||||
print(inclusiveRunningTotal)
|
||||
// prints [1, 3, 6, 10, 15]
|
||||
```
|
||||
|
||||
## Detailed Design
|
||||
|
||||
One trio of methods are added to `LazySequenceProtocol` for a lazily evaluated
|
||||
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
|
||||
) -> ExclusiveReductions<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>
|
||||
}
|
||||
```
|
||||
|
||||
```swift
|
||||
extension Sequence {
|
||||
|
||||
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(
|
||||
_ transform: (Element, Element) throws -> Element
|
||||
) rethrows -> [Element]
|
||||
}
|
||||
```
|
||||
|
||||
### Complexity
|
||||
|
||||
Calling the lazy methods, those defined on `LazySequenceProtocol`, is O(_1_).
|
||||
Calling the eager methods, those returning an array, is O(_n_).
|
||||
|
||||
### Naming
|
||||
|
||||
While the name `scan` is the term of art for this function, it has been
|
||||
discussed that `reductions` aligns better with the existing `reduce` function
|
||||
and will aid newcomers that might not know the existing `scan` term.
|
||||
|
||||
Deprecated `scan` methods have been added for people who are familiar with the
|
||||
term, so they can easily discover the `reductions` methods via compiler
|
||||
deprecation warnings.
|
||||
|
||||
Below are two quotes from the Swift forum [discussion about SE-0045][SE-0045]
|
||||
which proposed adding `scan` to the standard library and one from
|
||||
[issue #25][Issue 25] on the swift-algorithms GitHub project. These provide
|
||||
the reasoning to use the name `reductions`.
|
||||
|
||||
[Brent Royal-Gordon][Brent_Royal-Gordon]:
|
||||
> I really like the `reduce`/`reductions` pairing instead of `reduce`/`scan`;
|
||||
it does a really good job of explaining the relationship between the two
|
||||
functions.
|
||||
|
||||
[David Rönnqvist][David Rönnqvist]:
|
||||
> As other have already pointed out, I also feel that `scan` is the least
|
||||
intuitive name among these and that the `reduce`/`reductions` pairing would do
|
||||
a good job at explaining the relation between the two.
|
||||
|
||||
[Kyle Macomber][Kyle Macomber]:
|
||||
> As someone unfamiliar with the prior art, `reductions` strikes me as very
|
||||
approachable—I feel like I can extrapolate the expected behavior purely from my
|
||||
familiarity with `reduce`.
|
||||
|
||||
As part of early discussions, it was decided to have two variants, one which
|
||||
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`.
|
||||
|
||||
[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
|
||||
[Brent_Royal-Gordon]: https://forums.swift.org/t/review-se-0045-add-scan-prefix-while-drop-while-and-iterate-to-the-stdlib/2382/6
|
||||
[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 languages
|
||||
|
||||
**C++:** As of C++17, the `<algorithm>` library includes both
|
||||
[`exclusive_scan`][C++ Exclusive] and [`inclusive_scan`][C++ Inclusive]
|
||||
functions.
|
||||
|
||||
**[Clojure][Clojure]:** Clojure 1.2 added a `reductions` function.
|
||||
|
||||
**[Haskell][Haskell]:** Haskell includes a `scan` function for its
|
||||
`Traversable` type, which is akin to Swift's `Sequence`.
|
||||
|
||||
**Python:** Python’s `itertools` includes an `accumulate` method. In version
|
||||
3.3, a function parameter was added. Version 3.8 added the optional initial
|
||||
parameter.
|
||||
|
||||
**[Rust][Rust]:** Rust provides a `scan` function.
|
||||
|
||||
[C++ Exclusive]: https://en.cppreference.com/w/cpp/algorithm/exclusive_scan
|
||||
[C++ Inclusive]: https://en.cppreference.com/w/cpp/algorithm/inclusive_scan
|
||||
[Clojure]: http://clojure.github.io/clojure/clojure.core-api.html#clojure.core/reductions
|
||||
[Haskell]: http://hackage.haskell.org/package/base-4.8.2.0/docs/Prelude.html#v:scanl
|
||||
[Rust]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.scan
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 64 KiB After Width: | Height: | Size: 74 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 69 KiB After Width: | Height: | Size: 77 KiB |
+2
-21
@@ -48,25 +48,6 @@ func myAlgorithm2<Input>(input: Input) where Input: BidirectionalCollection {
|
||||
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
|
||||
|
||||
Calling this method is O(_n_).
|
||||
@@ -120,7 +101,7 @@ 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 concise code, which is more aligned with other programming
|
||||
Besides that, the root `trim` leads to clearer, more conscise code, which is more aligned with other programming
|
||||
languages:
|
||||
|
||||
```swift
|
||||
@@ -130,4 +111,4 @@ let result = input.dropFromBothEnds(while: { ... })
|
||||
|
||||
// No such ambiguity here.
|
||||
let result = input.trimming(while: { ... })
|
||||
```
|
||||
```
|
||||
+7
-14
@@ -5,7 +5,7 @@
|
||||
|
||||
Methods to strip repeated elements from a sequence or collection.
|
||||
|
||||
The `uniqued()` method returns a sequence, dropping duplicate elements
|
||||
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.
|
||||
@@ -14,36 +14,29 @@ element.
|
||||
let numbers = [1, 2, 3, 3, 2, 3, 3, 2, 2, 2, 1]
|
||||
|
||||
let unique = numbers.uniqued()
|
||||
// Array(unique) == [1, 2, 3]
|
||||
// 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. `uniqued(on:)` has a matching lazy
|
||||
version that is added to `LazySequenceProtocol`.
|
||||
the relative order of the elements.
|
||||
|
||||
```swift
|
||||
extension Sequence where Element: Hashable {
|
||||
func uniqued() -> Uniqued<Self, Element>
|
||||
func uniqued() -> [Element]
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
func uniqued<Subject>(on projection: (Element) throws -> Subject) rethrows -> [Element]
|
||||
where Subject: Hashable
|
||||
}
|
||||
|
||||
extension LazySequenceProtocol {
|
||||
func uniqued<Subject>(on projection: @escaping (Element) -> Subject) -> Uniqued<Self, Subject>
|
||||
where Subject: Hashable
|
||||
func uniqued<T>(on: (Element) throws -> T) rethrows -> [Element]
|
||||
where T: Hashable
|
||||
}
|
||||
```
|
||||
|
||||
### Complexity
|
||||
|
||||
The eager `uniqued(on:)` method is O(_n_) in both time and space complexity.
|
||||
The lazy versions are O(_1_).
|
||||
The `uniqued` methods are O(_n_) in both time and space complexity.
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
|
||||
@@ -28,6 +28,9 @@ let package = Package(
|
||||
dependencies: [
|
||||
.product(name: "RealModule", package: "swift-numerics"),
|
||||
]),
|
||||
.target(
|
||||
name: "Benchmark",
|
||||
dependencies: ["Algorithms"]),
|
||||
.testTarget(
|
||||
name: "SwiftAlgorithmsTests",
|
||||
dependencies: ["Algorithms"]),
|
||||
|
||||
@@ -10,7 +10,6 @@ Read more about the package, and the intent behind it, in the [announcement on s
|
||||
|
||||
- [`combinations(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Combinations.md): Combinations of particular sizes of the elements in a collection.
|
||||
- [`permutations(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Permutations.md): Permutations of a particular size of the elements in a collection, or of the full collection.
|
||||
- [`uniquePermutations(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Permutations.md): Permutations of a collection's elements, skipping any duplicate permutations.
|
||||
|
||||
#### Mutating algorithms
|
||||
|
||||
@@ -20,20 +19,15 @@ 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.
|
||||
- [`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.
|
||||
- [`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.
|
||||
|
||||
#### 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.
|
||||
- [`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
|
||||
|
||||
@@ -41,15 +35,13 @@ 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.
|
||||
- [`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/LazySplit.md): Lazy versions of the Standard Library's eager operations that split sequences and collections into subsequences separated by the specified separator element.
|
||||
- [`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.
|
||||
- [`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
|
||||
|
||||
@@ -66,7 +58,7 @@ If you don't want potentially source-breaking package updates,
|
||||
use this dependency specification instead:
|
||||
|
||||
```swift
|
||||
.package(url: "https://github.com/apple/swift-algorithms", .upToNextMinor(from: "0.1.0")),
|
||||
.package(url: "https://github.com/apple/swift-algorithms", .upToNextMinor(from: "0.0.1")),
|
||||
```
|
||||
|
||||
Finally, include `"Algorithms"` as a dependency for your executable target:
|
||||
@@ -75,7 +67,7 @@ Finally, include `"Algorithms"` as a dependency for your executable target:
|
||||
let package = Package(
|
||||
// name, platforms, products, etc.
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-algorithms", from: "0.1.0"),
|
||||
.package(url: "https://github.com/apple/swift-algorithms", from: "0.0.1"),
|
||||
// other dependencies
|
||||
],
|
||||
targets: [
|
||||
|
||||
@@ -1,315 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 {
|
||||
/// Creates a sequence of adjacent pairs of elements from 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)"
|
||||
@inlinable
|
||||
public func adjacentPairs() -> AdjacentPairsSequence<Self> {
|
||||
AdjacentPairsSequence(base: self)
|
||||
}
|
||||
}
|
||||
|
||||
extension Collection {
|
||||
/// A collection of adjacent pairs of elements built from an underlying
|
||||
/// 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)"
|
||||
@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`.
|
||||
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
|
||||
|
||||
public let startIndex: Index
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base) {
|
||||
self.base = base
|
||||
|
||||
// Lazily build the end index, since we can't use the instance
|
||||
// property pre-initialization
|
||||
var endIndex: Index {
|
||||
Index(first: base.endIndex, second: base.endIndex)
|
||||
}
|
||||
|
||||
// Precompute `startIndex` to ensure O(1) behavior.
|
||||
guard !base.isEmpty else {
|
||||
self.startIndex = endIndex
|
||||
return
|
||||
}
|
||||
|
||||
// If there's only one element (i.e. the second index of base == endIndex)
|
||||
// then this collection should be empty.
|
||||
let secondIndex = base.index(after: base.startIndex)
|
||||
self.startIndex = secondIndex == base.endIndex
|
||||
? endIndex
|
||||
: Index(first: base.startIndex, second: secondIndex)
|
||||
}
|
||||
}
|
||||
|
||||
extension AdjacentPairsCollection {
|
||||
public typealias Iterator = AdjacentPairsSequence<Base>.Iterator
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(base: base.makeIterator())
|
||||
}
|
||||
}
|
||||
|
||||
extension AdjacentPairsCollection {
|
||||
/// A position in an `AdjacentPairsCollection`.
|
||||
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 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: LazyCollectionProtocol {}
|
||||
|
||||
extension AdjacentPairsCollection.Index: Hashable where Base.Index: Hashable {
|
||||
@inlinable
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(first)
|
||||
}
|
||||
}
|
||||
@@ -14,14 +14,12 @@ public struct Chain2<Base1: Sequence, Base2: Sequence>
|
||||
where Base1.Element == Base2.Element
|
||||
{
|
||||
/// The first sequence in this chain.
|
||||
@usableFromInline
|
||||
internal let base1: Base1
|
||||
public let base1: Base1
|
||||
|
||||
/// The second sequence in this chain.
|
||||
@usableFromInline
|
||||
internal let base2: Base2
|
||||
public let base2: Base2
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(base1: Base1, base2: Base2) {
|
||||
self.base1 = base1
|
||||
self.base2 = base2
|
||||
@@ -37,7 +35,7 @@ extension Chain2: Sequence {
|
||||
@usableFromInline
|
||||
internal var iterator2: Base2.Iterator
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(_ concatenation: Chain2) {
|
||||
iterator1 = concatenation.base1.makeIterator()
|
||||
iterator2 = concatenation.base2.makeIterator()
|
||||
@@ -73,13 +71,13 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
|
||||
internal let position: Representation
|
||||
|
||||
/// Creates a new index into the first underlying collection.
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(first i: Base1.Index) {
|
||||
position = .first(i)
|
||||
}
|
||||
|
||||
/// Creates a new index into the second underlying collection.
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(second i: Base2.Index) {
|
||||
position = .second(i)
|
||||
}
|
||||
@@ -101,8 +99,8 @@ 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 normalizeIndex(_ i: Base1.Index) -> Index {
|
||||
@usableFromInline
|
||||
internal func convertIndex(_ i: Base1.Index) -> Index {
|
||||
i == base1.endIndex ? Index(second: base2.startIndex) : Index(first: i)
|
||||
}
|
||||
|
||||
@@ -110,7 +108,7 @@ 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`
|
||||
normalizeIndex(base1.startIndex)
|
||||
convertIndex(base1.startIndex)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@@ -133,116 +131,109 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
|
||||
switch i.position {
|
||||
case let .first(i):
|
||||
assert(i != base1.endIndex)
|
||||
return normalizeIndex(base1.index(after: i))
|
||||
return convertIndex(base1.index(after: i))
|
||||
case let .second(i):
|
||||
return Index(second: base2.index(after: i))
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
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)
|
||||
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)!
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func index(
|
||||
_ i: Index,
|
||||
offsetBy distance: Int,
|
||||
offsetBy n: Int,
|
||||
limitedBy limit: Index
|
||||
) -> Index? {
|
||||
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)
|
||||
}
|
||||
if n == 0 { return i }
|
||||
return n > 0
|
||||
? offsetForward(i, by: n, limitedBy: limit)
|
||||
: offsetBackward(i, by: -n, limitedBy: limit)
|
||||
}
|
||||
|
||||
@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
|
||||
@usableFromInline
|
||||
internal func offsetForward(
|
||||
_ i: Index, by distance: Int, limitedBy limit: Index
|
||||
_ i: Index, by n: 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: distance, limitedBy: limit)
|
||||
.map(Index.init(first:))
|
||||
|
||||
case let (.first(i), .second(limit)):
|
||||
if let j = base1.index(i, offsetBy: distance, limitedBy: base1.endIndex) {
|
||||
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 normalizeIndex(j)
|
||||
return convertIndex(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: distance - d, limitedBy: limit)
|
||||
return Index(second: base2.index(base2.startIndex, offsetBy: n - d))
|
||||
}
|
||||
|
||||
case let (.first(i), .second(limit)):
|
||||
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 base2.index(base2.startIndex, offsetBy: n - d, limitedBy: limit)
|
||||
.map(Index.init(second:))
|
||||
}
|
||||
|
||||
case (.second, .first):
|
||||
// impossible because `limit >= i`
|
||||
fatalError()
|
||||
case let (.second(i), .first):
|
||||
// `limit` has no effect here
|
||||
return Index(second: base2.index(i, offsetBy: n))
|
||||
|
||||
case let (.second(i), .second(limit)):
|
||||
return base2.index(i, offsetBy: distance, limitedBy: limit)
|
||||
return base2.index(i, offsetBy: n, limitedBy: limit)
|
||||
.map(Index.init(second:))
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal func offsetBackward(
|
||||
_ i: Index, by distance: Int, limitedBy limit: Index
|
||||
_ i: Index, by n: 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: -distance, limitedBy: limit)
|
||||
return base1.index(i, offsetBy: -n, limitedBy: limit)
|
||||
.map(Index.init(first:))
|
||||
|
||||
case (.first, .second):
|
||||
// impossible because `limit <= i`
|
||||
fatalError()
|
||||
case let (.first(i), .second):
|
||||
// `limit` has no effect here
|
||||
return Index(first: base1.index(i, offsetBy: -n))
|
||||
|
||||
case let (.second(i), .first(limit)):
|
||||
if let j = base2.index(i, offsetBy: -distance, limitedBy: base2.startIndex) {
|
||||
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 base1.index(base1.endIndex, offsetBy: -(distance - d), limitedBy: limit)
|
||||
return base1.index(base1.endIndex, offsetBy: -(n - d), limitedBy: limit)
|
||||
.map(Index.init(first:))
|
||||
}
|
||||
|
||||
case let (.second(i), .second(limit)):
|
||||
// `limit` is relevant, so `base1` cannot be reached
|
||||
return base2.index(i, offsetBy: -distance, limitedBy: limit)
|
||||
.map(Index.init(second:))
|
||||
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)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -283,6 +274,9 @@ extension Chain2: BidirectionalCollection
|
||||
extension Chain2: RandomAccessCollection
|
||||
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
|
||||
|
||||
extension Chain2: Equatable where Base1: Equatable, Base2: Equatable {}
|
||||
extension Chain2: Hashable where Base1: Hashable, Base2: Hashable {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// chain(_:_:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@@ -10,13 +10,10 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A collection wrapper that breaks a collection into chunks based on a
|
||||
/// predicate.
|
||||
///
|
||||
/// Call `lazy.chunked(by:)` on a collection to create an instance of this type.
|
||||
public struct ChunkedBy<Base: Collection, Subject> {
|
||||
/// predicate or projection.
|
||||
public struct LazyChunked<Base: Collection, Subject> {
|
||||
/// The collection that this instance provides a view onto.
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
public let base: Base
|
||||
|
||||
/// The projection function.
|
||||
@usableFromInline
|
||||
@@ -30,7 +27,7 @@ public struct ChunkedBy<Base: Collection, Subject> {
|
||||
@usableFromInline
|
||||
internal var firstUpperBound: Base.Index
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(
|
||||
base: Base,
|
||||
projection: @escaping (Base.Element) -> Subject,
|
||||
@@ -47,14 +44,14 @@ public struct ChunkedBy<Base: Collection, Subject> {
|
||||
}
|
||||
}
|
||||
|
||||
extension ChunkedBy: LazyCollectionProtocol {
|
||||
extension LazyChunked: LazyCollectionProtocol {
|
||||
/// A position in a chunked collection.
|
||||
public struct Index: Comparable {
|
||||
/// The range corresponding to the chunk at this position.
|
||||
@usableFromInline
|
||||
internal var baseRange: Range<Base.Index>
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(_ baseRange: Range<Base.Index>) {
|
||||
self.baseRange = baseRange
|
||||
}
|
||||
@@ -75,7 +72,7 @@ extension ChunkedBy: LazyCollectionProtocol {
|
||||
|
||||
/// Returns the index in the base collection of the end of the chunk starting
|
||||
/// at the given index.
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal func endOfChunk(startingAt start: Base.Index) -> Base.Index {
|
||||
let subject = projection(base[start])
|
||||
return base[base.index(after: start)...]
|
||||
@@ -108,14 +105,14 @@ extension ChunkedBy: LazyCollectionProtocol {
|
||||
}
|
||||
}
|
||||
|
||||
extension ChunkedBy.Index: Hashable where Base.Index: Hashable {}
|
||||
extension LazyChunked.Index: Hashable where Base.Index: Hashable {}
|
||||
|
||||
extension ChunkedBy: BidirectionalCollection
|
||||
extension LazyChunked: BidirectionalCollection
|
||||
where Base: BidirectionalCollection
|
||||
{
|
||||
/// Returns the index in the base collection of the start of the chunk ending
|
||||
/// at the given index.
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal func startOfChunk(endingAt end: Base.Index) -> Base.Index {
|
||||
let indexBeforeEnd = base.index(before: end)
|
||||
|
||||
@@ -133,64 +130,8 @@ extension ChunkedBy: BidirectionalCollection
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "ChunkedBy")
|
||||
public typealias LazyChunked<Base: Collection, Subject> = ChunkedBy<Base, Subject>
|
||||
|
||||
@available(*, deprecated, renamed: "ChunkedBy")
|
||||
public typealias Chunked<Base: Collection, Subject> = ChunkedBy<Base, Subject>
|
||||
|
||||
/// 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 ChunkedOn<Base: Collection, Subject> {
|
||||
@usableFromInline
|
||||
internal var chunked: ChunkedBy<Base, Subject>
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
base: Base,
|
||||
projection: @escaping (Base.Element) -> Subject,
|
||||
belongInSameGroup: @escaping (Subject, Subject) -> Bool
|
||||
) {
|
||||
self.chunked = ChunkedBy(base: base, projection: projection, belongInSameGroup: belongInSameGroup)
|
||||
}
|
||||
}
|
||||
|
||||
extension ChunkedOn: LazyCollectionProtocol {
|
||||
public typealias Index = ChunkedBy<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 ChunkedOn: BidirectionalCollection where Base: BidirectionalCollection {
|
||||
public func index(before i: Index) -> Index {
|
||||
chunked.index(before: i)
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// lazy.chunked(by:) / lazy.chunked(on:)
|
||||
// lazy.chunked(by:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension LazyCollectionProtocol {
|
||||
@@ -201,8 +142,8 @@ extension LazyCollectionProtocol {
|
||||
@inlinable
|
||||
public func chunked(
|
||||
by belongInSameGroup: @escaping (Element, Element) -> Bool
|
||||
) -> ChunkedBy<Elements, Element> {
|
||||
ChunkedBy(
|
||||
) -> LazyChunked<Elements, Element> {
|
||||
LazyChunked(
|
||||
base: elements,
|
||||
projection: { $0 },
|
||||
belongInSameGroup: belongInSameGroup)
|
||||
@@ -215,8 +156,8 @@ extension LazyCollectionProtocol {
|
||||
@inlinable
|
||||
public func chunked<Subject: Equatable>(
|
||||
on projection: @escaping (Element) -> Subject
|
||||
) -> ChunkedOn<Elements, Subject> {
|
||||
ChunkedOn(
|
||||
) -> LazyChunked<Elements, Subject> {
|
||||
LazyChunked(
|
||||
base: elements,
|
||||
projection: projection,
|
||||
belongInSameGroup: ==)
|
||||
@@ -224,29 +165,32 @@ extension LazyCollectionProtocol {
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// chunked(by:) / chunked(on:)
|
||||
// chunked(by:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Collection {
|
||||
/// Returns a collection of subsequences of this collection, chunked by
|
||||
/// the given predicate.
|
||||
/// grouping elements that project to the same value according to the given
|
||||
/// predicate.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
@inlinable
|
||||
public func chunked(
|
||||
by belongInSameGroup: (Element, Element) throws -> Bool
|
||||
@usableFromInline
|
||||
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 current = self[start]
|
||||
var subject = try projection(self[start])
|
||||
|
||||
for (index, element) in indexed().dropFirst() {
|
||||
if try !belongInSameGroup(current, element) {
|
||||
let nextSubject = try projection(element)
|
||||
if try !belongInSameGroup(subject, nextSubject) {
|
||||
result.append(self[start..<index])
|
||||
start = index
|
||||
current = element
|
||||
subject = nextSubject
|
||||
}
|
||||
}
|
||||
|
||||
@@ -256,6 +200,17 @@ extension Collection {
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/// 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
|
||||
public func chunked(
|
||||
by belongInSameGroup: (Element, Element) throws -> Bool
|
||||
) rethrows -> [SubSequence] {
|
||||
try chunked(on: { $0 }, by: belongInSameGroup)
|
||||
}
|
||||
|
||||
/// Returns a collection of subsequences of this collection, chunked by
|
||||
/// grouping elements that project to the same value.
|
||||
@@ -264,27 +219,8 @@ extension Collection {
|
||||
@inlinable
|
||||
public func chunked<Subject: Equatable>(
|
||||
on projection: (Element) throws -> Subject
|
||||
) 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..<endIndex]))
|
||||
}
|
||||
|
||||
return result
|
||||
) rethrows -> [SubSequence] {
|
||||
try chunked(on: projection, by: ==)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -337,7 +273,7 @@ extension ChunkedByCount: Collection {
|
||||
@usableFromInline
|
||||
internal let baseRange: Range<Base.Index>
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(_baseRange: Range<Base.Index>) {
|
||||
self.baseRange = _baseRange
|
||||
}
|
||||
@@ -354,7 +290,6 @@ extension ChunkedByCount: Collection {
|
||||
}
|
||||
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public subscript(i: Index) -> Element {
|
||||
precondition(i < endIndex, "Index out of range")
|
||||
return base[i.baseRange]
|
||||
@@ -457,7 +392,7 @@ extension ChunkedByCount {
|
||||
return index
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal func offsetForward(
|
||||
_ i: Index, offsetBy distance: Int, limit: Index? = nil
|
||||
) -> Index? {
|
||||
@@ -471,8 +406,8 @@ extension ChunkedByCount {
|
||||
}
|
||||
|
||||
// Convenience to compute offset backward base distance.
|
||||
@inlinable
|
||||
internal func computeOffsetBackwardBaseDistance(
|
||||
@inline(__always)
|
||||
private func computeOffsetBackwardBaseDistance(
|
||||
_ i: Index, _ distance: Int
|
||||
) -> Int {
|
||||
if i == endIndex {
|
||||
@@ -488,7 +423,7 @@ extension ChunkedByCount {
|
||||
return distance * chunkCount
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal func offsetBackward(
|
||||
_ i: Index, offsetBy distance: Int, limit: Index? = nil
|
||||
) -> Index? {
|
||||
@@ -503,8 +438,8 @@ extension ChunkedByCount {
|
||||
}
|
||||
|
||||
// Helper to compute index(offsetBy:) index.
|
||||
@inlinable
|
||||
internal func makeOffsetIndex(
|
||||
@inline(__always)
|
||||
private func makeOffsetIndex(
|
||||
from i: Index, baseBound: Base.Index, distance: Int, baseDistance: Int,
|
||||
limit: Index?, by limitFn: (Base.Index, Base.Index) -> Bool
|
||||
) -> Index? {
|
||||
@@ -572,6 +507,20 @@ extension Collection {
|
||||
}
|
||||
}
|
||||
|
||||
// Conditional conformances.
|
||||
extension ChunkedByCount: Equatable where Base: Equatable {}
|
||||
|
||||
// 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.
|
||||
|
||||
@@ -12,8 +12,7 @@
|
||||
/// A collection wrapper that generates combinations of a base collection.
|
||||
public struct Combinations<Base: Collection> {
|
||||
/// The collection to iterate over for combinations.
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
public let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let baseCount: Int
|
||||
@@ -28,7 +27,7 @@ public struct Combinations<Base: Collection> {
|
||||
/// - Parameters:
|
||||
/// - base: The collection to iterate over for combinations.
|
||||
/// - k: The expected size of each combination.
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(_ base: Base, k: Int) {
|
||||
self.init(base, kRange: k...k)
|
||||
}
|
||||
@@ -38,7 +37,7 @@ public struct Combinations<Base: Collection> {
|
||||
/// - Parameters:
|
||||
/// - base: The collection to iterate over for combinations.
|
||||
/// - kRange: The range of accepted sizes of combinations.
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init<R: RangeExpression>(
|
||||
_ base: Base, kRange: R
|
||||
) where R.Bound == Int {
|
||||
@@ -90,7 +89,7 @@ extension Combinations: Sequence {
|
||||
internal var kRange: Range<Int>
|
||||
|
||||
/// Whether or not iteration is finished (`kRange` is empty)
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal var isFinished: Bool {
|
||||
return kRange.isEmpty
|
||||
}
|
||||
@@ -98,7 +97,6 @@ extension Combinations: Sequence {
|
||||
@usableFromInline
|
||||
internal var indexes: [Base.Index]
|
||||
|
||||
@inlinable
|
||||
internal init(_ combinations: Combinations) {
|
||||
self.base = combinations.base
|
||||
self.kRange = combinations.kRange ?? 0..<0
|
||||
@@ -123,7 +121,7 @@ extension Combinations: Sequence {
|
||||
/// [2, 3, 4] *
|
||||
/// // Can't advance without needing to go past `base.endIndex`,
|
||||
/// // so the iteration is finished.
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal mutating func advance() {
|
||||
/// Advances `kRange` by incrementing its `lowerBound` until the range is
|
||||
/// empty, when iteration is finished.
|
||||
@@ -181,6 +179,8 @@ extension Combinations: Sequence {
|
||||
}
|
||||
|
||||
extension Combinations: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
extension Combinations: Equatable where Base: Equatable {}
|
||||
extension Combinations: Hashable where Base: Hashable {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// combinations(ofCount:)
|
||||
|
||||
@@ -1,181 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 {
|
||||
return Iterator(base: base.makeIterator())
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
/// Returns a new `Sequence` that iterates over every non-nil element
|
||||
/// from the original `Sequence`.
|
||||
/// It 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`.
|
||||
/// It 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
|
||||
where Base: LazySequenceProtocol {}
|
||||
extension CompactedCollection: LazyCollectionProtocol
|
||||
where Base: LazyCollectionProtocol {}
|
||||
@@ -12,10 +12,9 @@
|
||||
/// A collection wrapper that repeats the elements of a base collection.
|
||||
public struct Cycle<Base: Collection> {
|
||||
/// The collection to repeat.
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
public let base: Base
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(base: Base) {
|
||||
self.base = base
|
||||
}
|
||||
@@ -25,12 +24,12 @@ extension Cycle: Sequence {
|
||||
/// The iterator for a `Cycle` sequence.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal var current: Base.Index
|
||||
var current: Base.Index
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(base: Base) {
|
||||
self.base = base
|
||||
self.current = base.startIndex
|
||||
@@ -57,112 +56,6 @@ extension Cycle: Sequence {
|
||||
|
||||
extension Cycle: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
|
||||
|
||||
/// A collection wrapper that repeats the elements of a base collection for a
|
||||
/// finite number of times.
|
||||
public struct FiniteCycle<Base: Collection> {
|
||||
/// A Product2 instance for iterating the Base collection.
|
||||
@usableFromInline
|
||||
internal let product: Product2<Range<Int>, Base>
|
||||
|
||||
@inlinable
|
||||
internal init(base: Base, times: Int) {
|
||||
self.product = Product2(0..<times, base)
|
||||
}
|
||||
}
|
||||
|
||||
extension FiniteCycle: LazySequenceProtocol, LazyCollectionProtocol
|
||||
where Base: LazyCollectionProtocol { }
|
||||
|
||||
extension FiniteCycle: Collection {
|
||||
|
||||
public typealias Element = Base.Element
|
||||
|
||||
public struct Index: Comparable {
|
||||
/// The index corresponding to the Product2 index at this position.
|
||||
@usableFromInline
|
||||
internal let productIndex: Product2<Range<Int>, Base>.Index
|
||||
|
||||
@inlinable
|
||||
internal init(_ productIndex: Product2<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 FiniteCycle: BidirectionalCollection
|
||||
where Base: BidirectionalCollection {
|
||||
@inlinable
|
||||
public func index(before i: Index) -> Index {
|
||||
let productIndex = product.index(before: i.productIndex)
|
||||
return Index(productIndex)
|
||||
}
|
||||
}
|
||||
|
||||
extension FiniteCycle: RandomAccessCollection
|
||||
where Base: RandomAccessCollection {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// cycled()
|
||||
//===----------------------------------------------------------------------===//
|
||||
@@ -216,7 +109,7 @@ extension Collection {
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func cycled(times: Int) -> FiniteCycle<Self> {
|
||||
FiniteCycle(base: self, times: times)
|
||||
public func cycled(times: Int) -> FlattenSequence<Repeated<Self>> {
|
||||
repeatElement(self, count: times).joined()
|
||||
}
|
||||
}
|
||||
@@ -1,200 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 {}
|
||||
@@ -14,30 +14,15 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
public 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.
|
||||
/// Returns the first element in `self` that `transform` maps to a `.some`.
|
||||
func firstNonNil<Result>(
|
||||
_ transform: (Element) throws -> Result?
|
||||
) rethrows -> Result? {
|
||||
for value in self {
|
||||
if let value = try transform(value) {
|
||||
return value
|
||||
}
|
||||
for value in self {
|
||||
if let value = try transform(value) {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -1,306 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
where Base: LazySequenceProtocol, Base.Element: LazySequenceProtocol {}
|
||||
extension FlattenCollection: LazyCollectionProtocol
|
||||
where Base: LazyCollectionProtocol, Base.Element: LazyCollectionProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -16,10 +16,9 @@ public struct Indexed<Base: Collection> {
|
||||
public typealias Element = (index: Base.Index, element: Base.Element)
|
||||
|
||||
/// The base collection.
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
public let base: Base
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(base: Base) {
|
||||
self.base = base
|
||||
}
|
||||
@@ -72,6 +71,8 @@ extension Indexed: BidirectionalCollection where Base: BidirectionalCollection {
|
||||
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 {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// indexed()
|
||||
|
||||
@@ -9,10 +9,6 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Intersperse
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// 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> {
|
||||
@@ -22,7 +18,7 @@ public struct Intersperse<Base: Sequence> {
|
||||
@usableFromInline
|
||||
internal let separator: Base.Element
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(base: Base, separator: Base.Element) {
|
||||
self.base = base
|
||||
self.separator = separator
|
||||
@@ -41,7 +37,7 @@ extension Intersperse: Sequence {
|
||||
@usableFromInline
|
||||
internal var state = State.start
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(iterator: Base.Iterator, separator: Base.Element) {
|
||||
self.iterator = iterator
|
||||
self.separator = separator
|
||||
@@ -85,7 +81,7 @@ extension Intersperse: Collection where Base: Collection {
|
||||
/// A position in an `Intersperse` collection.
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal enum Representation: Equatable {
|
||||
enum Representation: Equatable {
|
||||
case element(Base.Index)
|
||||
case separator(next: Base.Index)
|
||||
}
|
||||
@@ -93,11 +89,6 @@ extension Intersperse: Collection where Base: Collection {
|
||||
@usableFromInline
|
||||
internal let representation: Representation
|
||||
|
||||
@inlinable
|
||||
internal init(representation: Representation) {
|
||||
self.representation = representation
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Index, rhs: Index) -> Bool {
|
||||
switch (lhs.representation, rhs.representation) {
|
||||
@@ -110,13 +101,13 @@ extension Intersperse: Collection where Base: Collection {
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal static func element(_ index: Base.Index) -> Self {
|
||||
@usableFromInline
|
||||
static func element(_ index: Base.Index) -> Self {
|
||||
Self(representation: .element(index))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal static func separator(next: Base.Index) -> Self {
|
||||
@usableFromInline
|
||||
static func separator(next: Base.Index) -> Self {
|
||||
Self(representation: .separator(next: next))
|
||||
}
|
||||
}
|
||||
@@ -150,6 +141,21 @@ 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) {
|
||||
@@ -162,98 +168,6 @@ 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
|
||||
@@ -280,315 +194,6 @@ extension Intersperse: LazySequenceProtocol
|
||||
extension Intersperse: LazyCollectionProtocol
|
||||
where Base: LazyCollectionProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// 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 InterspersedMap<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 InterspersedMap: Sequence {
|
||||
@usableFromInline
|
||||
internal struct Iterator: IteratorProtocol {
|
||||
@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
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal enum State {
|
||||
case start
|
||||
case element(Base.Element)
|
||||
case separator(previous: Base.Element)
|
||||
}
|
||||
|
||||
@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 InterspersedMap: Collection where Base: Collection {
|
||||
@usableFromInline
|
||||
internal struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal enum Representation: Equatable {
|
||||
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 InterspersedMap: 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 InterspersedMap.Index.Representation: Hashable
|
||||
where Base.Index: Hashable {}
|
||||
|
||||
extension InterspersedMap: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
extension InterspersedMap: LazyCollectionProtocol
|
||||
where Base: LazyCollectionProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// interspersed(with:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Sequence {
|
||||
|
||||
/// Returns a sequence containing elements of this sequence with the given
|
||||
@@ -624,30 +229,3 @@ extension Sequence {
|
||||
Intersperse(base: self, separator: separator)
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// lazy.interspersed(_: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
|
||||
) -> InterspersedMap<Self, Result> {
|
||||
InterspersedMap(base: self, transform: transform, separator: separator)
|
||||
}
|
||||
}
|
||||
@@ -1,495 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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<
|
||||
Intersperse<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<
|
||||
InterspersedMap<LazySequence<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
|
||||
where Base: 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<
|
||||
Intersperse<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
|
||||
where Base: LazySequenceProtocol {}
|
||||
extension JoinedByCollection: LazyCollectionProtocol
|
||||
where Base: LazyCollectionProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// 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<
|
||||
InterspersedMap<LazySequence<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: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
extension JoinedByClosureCollection: LazyCollectionProtocol
|
||||
where Base: 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<Self, 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<Self, Separator> {
|
||||
JoinedByClosureSequence(base: self, 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)
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// LazyCollectionProtocol.joined(by:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension LazyCollectionProtocol where 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<Self, 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<Self, Separator> {
|
||||
JoinedByClosureCollection(base: self, separator: separator)
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,7 @@ public struct LazySplitSequence<Base: Sequence> {
|
||||
@usableFromInline
|
||||
internal let omittingEmptySubsequences: Bool
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(
|
||||
base: Base,
|
||||
isSeparator: @escaping (Base.Element) -> Bool,
|
||||
@@ -72,7 +72,7 @@ extension LazySplitSequence {
|
||||
@usableFromInline
|
||||
internal var sequenceLength = 0
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(
|
||||
base: Base.Iterator,
|
||||
whereSeparator: @escaping (Base.Element) -> Bool,
|
||||
@@ -360,7 +360,7 @@ public struct LazySplitCollection<Base: Collection> {
|
||||
@usableFromInline
|
||||
internal var _startIndex: Index
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(
|
||||
base: Base,
|
||||
isSeparator: @escaping (Base.Element) -> Bool,
|
||||
@@ -415,7 +415,7 @@ extension LazySplitCollection: LazyCollectionProtocol {
|
||||
@usableFromInline
|
||||
internal let splitCount: Int
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(
|
||||
baseRange: Range<Base.Index>,
|
||||
sequenceLength: Int,
|
||||
@@ -441,7 +441,7 @@ extension LazySplitCollection: LazyCollectionProtocol {
|
||||
|
||||
/// Returns the index of the subsequence starting at or after the given base
|
||||
/// collection index.
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal func indexForSubsequence(
|
||||
atOrAfter lowerBound: Base.Index,
|
||||
sequenceLength: Int,
|
||||
|
||||
@@ -120,7 +120,7 @@ extension Sequence {
|
||||
return try _minImplementation(count: count, sortedBy: areInIncreasingOrder)
|
||||
}
|
||||
|
||||
/// Returns the largest elements of this sequence, as sorted by the given
|
||||
/// Returns the largets elements of this sequence, as sorted by the given
|
||||
/// predicate.
|
||||
///
|
||||
/// This example partially sorts an array of integers to retrieve its three
|
||||
@@ -275,7 +275,7 @@ extension Collection {
|
||||
return try _minImplementation(count: count, sortedBy: areInIncreasingOrder)
|
||||
}
|
||||
|
||||
/// Returns the largest elements of this collection, as sorted by the given
|
||||
/// Returns the largets elements of this collection, as sorted by the given
|
||||
/// predicate.
|
||||
///
|
||||
/// This example partially sorts an array of integers to retrieve its three
|
||||
@@ -383,102 +383,3 @@ extension Collection where Element: Comparable {
|
||||
return 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.
|
||||
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)? {
|
||||
return minAndMax(by: <)
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ extension MutableCollection {
|
||||
/// - Complexity: O(*n* log *n*), where *n* is the number of elements.
|
||||
/// - Precondition:
|
||||
/// `n == distance(from: range.lowerBound, to: range.upperBound)`
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal mutating func stablePartition(
|
||||
count n: Int,
|
||||
subrange: Range<Index>,
|
||||
|
||||
@@ -9,77 +9,10 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// nextPermutation()
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension MutableCollection
|
||||
where Self: BidirectionalCollection, Element: Comparable
|
||||
{
|
||||
/// 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
|
||||
/// `false`.
|
||||
///
|
||||
/// - Returns: A Boolean value indicating whether the collection still has
|
||||
/// remaining permutations. When this method returns `false`, the collection
|
||||
/// is in ascending order according to `areInIncreasingOrder`.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
internal mutating func nextPermutation(upperBound: Index? = nil) -> Bool {
|
||||
// Ensure we have > 1 element in the collection.
|
||||
guard !isEmpty else { return false }
|
||||
var i = index(before: endIndex)
|
||||
if i == startIndex { return false }
|
||||
|
||||
let upperBound = upperBound ?? endIndex
|
||||
|
||||
while true {
|
||||
let ip1 = i
|
||||
formIndex(before: &i)
|
||||
|
||||
// Find the last ascending pair (ie. ..., a, b, ... where a < b)
|
||||
if self[i] < self[ip1] {
|
||||
// Find the last element greater than self[i]
|
||||
// This is _always_ at most `ip1` due to if statement above
|
||||
let j = lastIndex(where: { self[i] < $0 })!
|
||||
|
||||
// At this point we have something like this:
|
||||
// 0, 1, 4, 3, 2
|
||||
// ^ ^
|
||||
// i j
|
||||
swapAt(i, j)
|
||||
self.reverse(subrange: ip1 ..< endIndex)
|
||||
|
||||
// Only return if we've made a change within ..<upperBound region
|
||||
if i < upperBound {
|
||||
return true
|
||||
} else {
|
||||
i = index(before: endIndex)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if i == startIndex {
|
||||
self.reverse()
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// struct Permutations<Base>
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A sequence of all the permutations of a collection's elements.
|
||||
public struct Permutations<Base: Collection> {
|
||||
/// The base collection to iterate over for permutations.
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
public let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let baseCount: Int
|
||||
@@ -95,7 +28,7 @@ public struct Permutations<Base: Collection> {
|
||||
/// - base: The collection to iterate over for permutations
|
||||
/// - k: The expected size of each permutation, or `nil` (default) to
|
||||
/// iterate over all permutations of the same size as the base collection.
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(_ base: Base, k: Int? = nil) {
|
||||
let kRange: ClosedRange<Int>?
|
||||
if let countToChoose = k {
|
||||
@@ -112,7 +45,7 @@ public struct Permutations<Base: Collection> {
|
||||
/// - base: The collection to iterate over for permutations.
|
||||
/// - kRange: The range of accepted sizes of permutations, or `nil` to
|
||||
/// iterate over all permutations of the same size as the base collection.
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init<R: RangeExpression>(
|
||||
_ base: Base, kRange: R?
|
||||
) where R.Bound == Int {
|
||||
@@ -138,7 +71,7 @@ extension Permutations: Sequence {
|
||||
/// The iterator for a `Permutations` instance.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
internal var base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let baseCount: Int
|
||||
@@ -151,7 +84,7 @@ extension Permutations: Sequence {
|
||||
internal var kRange: Range<Int>
|
||||
|
||||
/// Whether or not iteration is finished (`kRange` is empty)
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal var isFinished: Bool {
|
||||
return kRange.isEmpty
|
||||
}
|
||||
@@ -159,7 +92,7 @@ extension Permutations: Sequence {
|
||||
@usableFromInline
|
||||
internal var indexes: [Base.Index]
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(_ permutations: Permutations) {
|
||||
self.base = permutations.base
|
||||
self.baseCount = permutations.baseCount
|
||||
@@ -178,7 +111,7 @@ extension Permutations: Sequence {
|
||||
/// is in ascending order.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal mutating func nextState() -> Bool {
|
||||
let countToChoose = self.kRange.lowerBound
|
||||
let edge = countToChoose - 1
|
||||
@@ -261,6 +194,54 @@ extension Permutations: Sequence {
|
||||
|
||||
extension Permutations: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// nextPermutation()
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension MutableCollection
|
||||
where Self: BidirectionalCollection, Element: Comparable
|
||||
{
|
||||
/// 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
|
||||
/// `false`.
|
||||
///
|
||||
/// - Returns: A Boolean value indicating whether the collection still has
|
||||
/// remaining permutations. When this method returns `false`, the collection
|
||||
/// is in ascending order according to `areInIncreasingOrder`.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@usableFromInline
|
||||
internal mutating func nextPermutation() -> Bool {
|
||||
// Ensure we have > 1 element in the collection.
|
||||
guard !isEmpty else { return false }
|
||||
var i = index(before: endIndex)
|
||||
if i == startIndex { return false }
|
||||
|
||||
while true {
|
||||
let ip1 = i
|
||||
formIndex(before: &i)
|
||||
|
||||
if self[i] < self[ip1] {
|
||||
var j = index(before: endIndex)
|
||||
while self[i] >= self[j] {
|
||||
formIndex(before: &j)
|
||||
}
|
||||
swapAt(i, j)
|
||||
self.reverse(subrange: ip1 ..< endIndex)
|
||||
return true
|
||||
}
|
||||
|
||||
if i == startIndex {
|
||||
self.reverse()
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// permutations(ofCount:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
@@ -287,41 +268,34 @@ extension Collection {
|
||||
/// // Davide, Celeste
|
||||
///
|
||||
/// This example prints _all_ the permutations (including an empty array) from
|
||||
/// an array of numbers:
|
||||
/// the an array of numbers:
|
||||
///
|
||||
/// let numbers = [10, 20, 30]
|
||||
/// for perm in numbers.permutations(ofCount: 0...) {
|
||||
/// print(perm)
|
||||
/// }
|
||||
/// // []
|
||||
/// // [10]
|
||||
/// // [20]
|
||||
/// // [30]
|
||||
/// // [10, 20]
|
||||
/// // [10, 30]
|
||||
/// // [20, 10]
|
||||
/// // [20, 30]
|
||||
/// // [30, 10]
|
||||
/// // [30, 20]
|
||||
/// // [10, 20, 30]
|
||||
/// // [10, 30, 20]
|
||||
/// // [20, 10, 30]
|
||||
/// // [20, 30, 10]
|
||||
/// // [30, 10, 20]
|
||||
/// // [30, 20, 10]
|
||||
/// for perm in numbers.permutations(ofCount: 0...) {
|
||||
/// print(perm)
|
||||
/// }
|
||||
/// // []
|
||||
/// // [10]
|
||||
/// // [20]
|
||||
/// // [30]
|
||||
/// // [10, 20]
|
||||
/// // [10, 30]
|
||||
/// // [20, 10]
|
||||
/// // [20, 30]
|
||||
/// // [30, 10]
|
||||
/// // [30, 20]
|
||||
/// // [10, 20, 30]
|
||||
/// // [10, 30, 20]
|
||||
/// // [20, 10, 30]
|
||||
/// // [20, 30, 10]
|
||||
/// // [30, 10, 20]
|
||||
/// // [30, 20, 10]
|
||||
///
|
||||
/// The returned permutations are in ascending order by length, and then
|
||||
/// lexicographically within each group of the same length.
|
||||
///
|
||||
/// - Parameter kRange: A range of the number of elements to include in each
|
||||
/// permutation. `kRange` can be any integer range expression, and is
|
||||
/// clamped to the number of elements in this collection. Passing a range
|
||||
/// covering sizes greater than the number of elements in this collection
|
||||
/// results in an empty sequence.
|
||||
/// - Parameter kRange: The number of elements to include in each permutation.
|
||||
///
|
||||
/// - 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 `Permutations`
|
||||
/// accesses the `count` of the base collection.
|
||||
@inlinable
|
||||
public func permutations<R: RangeExpression>(
|
||||
ofCount kRange: R
|
||||
@@ -372,12 +346,11 @@ extension Collection {
|
||||
///
|
||||
/// - Parameter k: The number of elements to include in each permutation.
|
||||
/// If `k` is `nil`, the resulting sequence represents permutations of this
|
||||
/// entire collection. If `k` is greater than the number of elements in
|
||||
/// this collection, the resulting sequence is empty.
|
||||
/// entire collection.
|
||||
///
|
||||
/// - 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 `Permutations`
|
||||
/// accesses the `count` of the base collection.
|
||||
@inlinable
|
||||
public func permutations(ofCount k: Int? = nil) -> Permutations<Self> {
|
||||
precondition(
|
||||
@@ -386,197 +359,3 @@ extension Collection {
|
||||
return Permutations(self, k: k)
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// uniquePermutations()
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A sequence of the unique permutations of the elements of a sequence or
|
||||
/// collection.
|
||||
///
|
||||
/// To create a `UniquePermutations` instance, call one of the
|
||||
/// `uniquePermutations` methods on your collection.
|
||||
public struct UniquePermutations<Base: Collection> {
|
||||
/// The base collection to iterate over for permutations.
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal var indexes: [Base.Index]
|
||||
|
||||
@usableFromInline
|
||||
internal let kRange: Range<Int>
|
||||
}
|
||||
|
||||
extension UniquePermutations where Base.Element: Hashable {
|
||||
@inlinable
|
||||
internal static func _indexes(_ base: Base) -> [Base.Index] {
|
||||
let firstIndexesAndCountsByElement = Dictionary(
|
||||
base.indices.lazy.map { (base[$0], ($0, 1)) },
|
||||
uniquingKeysWith: { indexAndCount, _ in (indexAndCount.0, indexAndCount.1 + 1) })
|
||||
|
||||
return firstIndexesAndCountsByElement
|
||||
.values.sorted(by: { $0.0 < $1.0 })
|
||||
.flatMap { index, count in repeatElement(index, count: count) }
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal init(_ elements: Base) {
|
||||
self.indexes = Self._indexes(elements)
|
||||
self.base = elements
|
||||
self.kRange = self.indexes.count ..< (self.indexes.count + 1)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal init<R: RangeExpression>(_ base: Base, _ range: R)
|
||||
where R.Bound == Int
|
||||
{
|
||||
self.indexes = Self._indexes(base)
|
||||
self.base = base
|
||||
|
||||
let upperBound = self.indexes.count + 1
|
||||
self.kRange = range.relative(to: 0 ..< .max)
|
||||
.clamped(to: 0 ..< upperBound)
|
||||
}
|
||||
}
|
||||
|
||||
extension UniquePermutations: Sequence {
|
||||
/// The iterator for a `UniquePermutations` instance.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal var indexes: [Base.Index]
|
||||
|
||||
@usableFromInline
|
||||
internal var lengths: Range<Int>
|
||||
|
||||
@usableFromInline
|
||||
internal var initial = true
|
||||
|
||||
@inlinable
|
||||
internal init(_ elements: Base, indexes: [Base.Index], lengths: Range<Int>) {
|
||||
self.base = elements
|
||||
self.indexes = indexes
|
||||
self.lengths = lengths
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> [Base.Element]? {
|
||||
// In the end case, `lengths` is an empty range.
|
||||
if lengths.isEmpty {
|
||||
return nil
|
||||
}
|
||||
|
||||
// The first iteration must produce the original sorted array, before any
|
||||
// permutations. We skip the permutation the first time so that we can
|
||||
// always mutate the array _before_ returning a slice, which avoids
|
||||
// copying when possible.
|
||||
if initial {
|
||||
initial = false
|
||||
return indexes[..<lengths.lowerBound].map { base[$0] }
|
||||
}
|
||||
|
||||
if !indexes.nextPermutation(upperBound: lengths.lowerBound) {
|
||||
lengths.removeFirst()
|
||||
|
||||
if lengths.isEmpty {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return indexes[..<lengths.lowerBound].map { base[$0] }
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(base, indexes: indexes, lengths: kRange)
|
||||
}
|
||||
}
|
||||
|
||||
extension UniquePermutations: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
|
||||
extension Collection where Element: Hashable {
|
||||
/// Returns a sequence of the unique permutations of this sequence of the
|
||||
/// specified length.
|
||||
///
|
||||
/// Use this method to iterate over the unique permutations of a sequence
|
||||
/// with repeating elements. This example prints every unique two-element
|
||||
/// permutation of an array of numbers:
|
||||
///
|
||||
/// let numbers = [1, 1, 2]
|
||||
/// for perm in numbers.uniquePermutations(ofCount: 2) {
|
||||
/// print(perm)
|
||||
/// }
|
||||
/// // [1, 1]
|
||||
/// // [1, 2]
|
||||
/// // [2, 1]
|
||||
///
|
||||
/// By contrast, the `permutations(ofCount:)` method permutes a collection's
|
||||
/// elements by position, and can include permutations with equal elements
|
||||
/// in each permutation:
|
||||
///
|
||||
/// for perm in numbers.permutations(ofCount: 2)
|
||||
/// print(perm)
|
||||
/// }
|
||||
/// // [1, 1]
|
||||
/// // [1, 1]
|
||||
/// // [1, 2]
|
||||
/// // [1, 2]
|
||||
/// // [2, 1]
|
||||
/// // [2, 1]
|
||||
///
|
||||
/// The returned permutations are in lexicographically sorted order.
|
||||
///
|
||||
/// - Parameter k: The number of elements to include in each permutation.
|
||||
/// If `k` is `nil`, the resulting sequence represents permutations of this
|
||||
/// entire collection. If `k` is greater than the number of elements in
|
||||
/// this collection, the resulting sequence is empty.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the number of elements in this
|
||||
/// collection.
|
||||
public func uniquePermutations(ofCount k: Int? = nil) -> UniquePermutations<Self> {
|
||||
if let k = k {
|
||||
return UniquePermutations(self, k ..< (k + 1))
|
||||
} else {
|
||||
return UniquePermutations(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a collection of the unique permutations of this sequence with
|
||||
/// lengths in the specified range.
|
||||
///
|
||||
/// Use this method to iterate over the unique permutations of a sequence
|
||||
/// with repeating elements. This example prints every unique permutation
|
||||
/// of an array of numbers with lengths through 2 elements:
|
||||
///
|
||||
/// let numbers = [1, 1, 2]
|
||||
/// for perm in numbers.uniquePermutations(ofCount: ...2) {
|
||||
/// print(perm)
|
||||
/// }
|
||||
/// // []
|
||||
/// // [1]
|
||||
/// // [2]
|
||||
/// // [1, 1]
|
||||
/// // [1, 2]
|
||||
/// // [2, 1]
|
||||
///
|
||||
/// The returned permutations are in ascending order by length, and then
|
||||
/// lexicographically within each group of the same length.
|
||||
///
|
||||
/// - Parameter kRange: A range of the number of elements to include in each
|
||||
/// permutation. `kRange` can be any integer range expression, and is
|
||||
/// clamped to the number of elements in this collection. Passing a range
|
||||
/// covering sizes greater than the number of elements in this collection
|
||||
/// results in an empty sequence.
|
||||
///
|
||||
/// - 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)
|
||||
}
|
||||
}
|
||||
@@ -12,14 +12,11 @@
|
||||
/// A sequence that represents the product of two sequences' elements.
|
||||
public struct Product2<Base1: Sequence, Base2: Collection> {
|
||||
/// The outer sequence in the product.
|
||||
@usableFromInline
|
||||
internal let base1: Base1
|
||||
|
||||
public let base1: Base1
|
||||
/// The inner sequence in the product.
|
||||
@usableFromInline
|
||||
internal let base2: Base2
|
||||
public let base2: Base2
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(_ base1: Base1, _ base2: Base2) {
|
||||
self.base1 = base1
|
||||
self.base2 = base2
|
||||
@@ -27,8 +24,6 @@ public struct Product2<Base1: Sequence, Base2: Collection> {
|
||||
}
|
||||
|
||||
extension Product2: Sequence {
|
||||
public typealias Element = (Base1.Element, Base2.Element)
|
||||
|
||||
/// The iterator for a `Product2` sequence.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
@@ -40,7 +35,7 @@ extension Product2: Sequence {
|
||||
@usableFromInline
|
||||
internal let base2: Base2
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(_ c: Product2) {
|
||||
self.base2 = c.base2
|
||||
self.i1 = c.base1.makeIterator()
|
||||
@@ -49,8 +44,7 @@ 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.
|
||||
@@ -96,7 +90,7 @@ extension Product2: Collection where Base1: Collection {
|
||||
@usableFromInline
|
||||
internal var i2: Base2.Index
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(i1: Base1.Index, i2: Base2.Index) {
|
||||
self.i1 = i1
|
||||
self.i2 = i2
|
||||
@@ -127,15 +121,14 @@ 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])
|
||||
}
|
||||
|
||||
/// Forms an index from a pair of base indices, normalizing
|
||||
/// `(i, base2.endIndex)` to `(base1.index(after: i), base2.startIndex)` if
|
||||
/// necessary.
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal func normalizeIndex(_ i1: Base1.Index, _ i2: Base2.Index) -> Index {
|
||||
i2 == base2.endIndex
|
||||
? Index(i1: base1.index(after: i1), i2: base2.startIndex)
|
||||
@@ -202,7 +195,6 @@ extension Product2: Collection where Base1: Collection {
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||
guard distance != 0 else { return i }
|
||||
|
||||
@@ -211,7 +203,6 @@ extension Product2: Collection where Base1: Collection {
|
||||
: offsetBackward(i, by: -distance)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(
|
||||
_ i: Index,
|
||||
offsetBy distance: Int,
|
||||
@@ -228,21 +219,21 @@ extension Product2: Collection where Base1: Collection {
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
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
|
||||
@usableFromInline
|
||||
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
|
||||
@usableFromInline
|
||||
internal func offsetForward(
|
||||
_ i: Index, by distance: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
@@ -320,7 +311,7 @@ extension Product2: Collection where Base1: Collection {
|
||||
.map { i2 in Index(i1: i1, i2: i2) }
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal func offsetBackward(
|
||||
_ i: Index, by distance: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
@@ -440,6 +431,8 @@ extension Product2: 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 {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// product(_:_:)
|
||||
|
||||
@@ -1,643 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// MARK: - Exclusive Reductions
|
||||
|
||||
extension LazySequenceProtocol {
|
||||
|
||||
/// Returns a sequence containing the accumulated results of combining the
|
||||
/// elements of the sequence using the given closure.
|
||||
///
|
||||
/// This can be seen as applying the reduce function to each element and
|
||||
/// providing the initial value followed by these results as a sequence.
|
||||
///
|
||||
/// ```
|
||||
/// let runningTotal = [1, 2, 3, 4].lazy.reductions(0, +)
|
||||
/// print(Array(runningTotal))
|
||||
///
|
||||
/// // prints [0, 1, 3, 6, 10]
|
||||
/// ```
|
||||
///
|
||||
/// - 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.
|
||||
/// - Returns: A sequence of the initial value followed by the reduced
|
||||
/// 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
|
||||
result = transform(result, element)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a sequence containing the accumulated results of combining the
|
||||
/// elements of the sequence using the given closure.
|
||||
///
|
||||
/// This can be seen as applying the reduce function to each element and
|
||||
/// providing the initial value followed by these results as a sequence.
|
||||
///
|
||||
/// ```
|
||||
/// let runningTotal = [1, 2, 3, 4].lazy.reductions(into: 0, +)
|
||||
/// print(Array(runningTotal))
|
||||
///
|
||||
/// // prints [0, 1, 3, 6, 10]
|
||||
/// ```
|
||||
///
|
||||
/// - 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.
|
||||
/// - Returns: A sequence of the initial value followed by the reduced
|
||||
/// elements.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func reductions<Result>(
|
||||
into initial: Result,
|
||||
_ transform: @escaping (inout Result, Element) -> Void
|
||||
) -> ExclusiveReductions<Result, Self> {
|
||||
ExclusiveReductions(base: self, initial: initial, transform: transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
|
||||
/// Returns an array containing the accumulated results of combining the
|
||||
/// elements of the sequence using the given closure.
|
||||
///
|
||||
/// This can be seen as applying the reduce function to each element and
|
||||
/// providing the initial value followed by these results as a sequence.
|
||||
///
|
||||
/// ```
|
||||
/// let runningTotal = [1, 2, 3, 4].reductions(0, +)
|
||||
/// print(runningTotal)
|
||||
///
|
||||
/// // prints [0, 1, 3, 6, 10]
|
||||
/// ```
|
||||
///
|
||||
/// When `reductions(_:_:)` is called, the following steps occur:
|
||||
///
|
||||
/// 1. The `initial` result is added to an array of results.
|
||||
/// 2. The `transform` closure is called with the `initial` result and the
|
||||
/// first element of the sequence, appending the result to the array.
|
||||
/// 3. The closure is called again repeatedly with the updated accumulating
|
||||
/// result and each element of the sequence, adding each result to the
|
||||
/// array.
|
||||
/// 4. When the sequence is exhausted, the results array is returned to the
|
||||
/// caller.
|
||||
///
|
||||
/// If the sequence has no elements, `transform` is never executed and
|
||||
/// an array containing only the `initial` result is returned.
|
||||
///
|
||||
/// - 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.
|
||||
/// - Returns: An array of the initial value followed by the reduced elements.
|
||||
///
|
||||
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
|
||||
@inlinable
|
||||
public func reductions<Result>(
|
||||
_ initial: Result,
|
||||
_ transform: (Result, Element) throws -> Result
|
||||
) rethrows -> [Result] {
|
||||
return try reductions(into: initial) { result, element in
|
||||
result = try transform(result, element)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an array containing the accumulated results of combining the
|
||||
/// elements of the sequence using the given closure.
|
||||
///
|
||||
/// This can be seen as applying the reduce function to each element and
|
||||
/// providing the initial value followed by these results as a sequence.
|
||||
///
|
||||
/// ```
|
||||
/// let runningTotal = [1, 2, 3, 4].reductions(into: 0, +)
|
||||
/// print(runningTotal)
|
||||
///
|
||||
/// // prints [0, 1, 3, 6, 10]
|
||||
/// ```
|
||||
///
|
||||
/// When `reductions(into:_:_)` is called, the following steps occur:
|
||||
///
|
||||
/// 1. The `initial` result is added to an array of results.
|
||||
/// 2. The `transform` closure is called with the `initial` result and the
|
||||
/// first element of the sequence, appending the result to the array.
|
||||
/// 3. The closure is called again repeatedly with the updated accumulating
|
||||
/// result and each element of the sequence, adding each result to the
|
||||
/// array.
|
||||
/// 4. When the sequence is exhausted, the results array is returned to the
|
||||
/// caller.
|
||||
///
|
||||
/// If the sequence has no elements, `transform` is never executed and
|
||||
/// an array containing only the `initial` result is returned.
|
||||
///
|
||||
/// - 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.
|
||||
/// - Returns: An array of the initial value followed by the reduced elements.
|
||||
///
|
||||
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
|
||||
@inlinable
|
||||
public func reductions<Result>(
|
||||
into initial: Result,
|
||||
_ transform: (inout Result, Element) throws -> Void
|
||||
) rethrows -> [Result] {
|
||||
|
||||
var output = [Result]()
|
||||
output.reserveCapacity(underestimatedCount + 1)
|
||||
output.append(initial)
|
||||
|
||||
var initial = initial
|
||||
for element in self {
|
||||
try transform(&initial, element)
|
||||
output.append(initial)
|
||||
}
|
||||
|
||||
return output
|
||||
}
|
||||
}
|
||||
|
||||
/// A sequence of applying a transform to the element of a sequence and the
|
||||
/// previously transformed result.
|
||||
public struct ExclusiveReductions<Result, Base: Sequence> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let initial: Result
|
||||
|
||||
@usableFromInline
|
||||
internal let transform: (inout Result, Base.Element) -> Void
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
base: Base,
|
||||
initial: Result,
|
||||
transform: @escaping (inout Result, Base.Element) -> Void
|
||||
) {
|
||||
self.base = base
|
||||
self.initial = initial
|
||||
self.transform = transform
|
||||
}
|
||||
}
|
||||
|
||||
extension ExclusiveReductions: Sequence {
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var iterator: Base.Iterator
|
||||
|
||||
@usableFromInline
|
||||
internal var current: Result?
|
||||
|
||||
@usableFromInline
|
||||
internal let transform: (inout Result, Base.Element) -> Void
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
iterator: Base.Iterator,
|
||||
current: Result? = nil,
|
||||
transform: @escaping (inout Result, Base.Element) -> Void
|
||||
) {
|
||||
self.iterator = iterator
|
||||
self.current = current
|
||||
self.transform = transform
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Result? {
|
||||
guard let result = current else { return nil }
|
||||
current = iterator.next().map { element in
|
||||
var result = result
|
||||
transform(&result, element)
|
||||
return result
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(iterator: base.makeIterator(),
|
||||
current: initial,
|
||||
transform: transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension ExclusiveReductions: Collection where Base: Collection {
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal let representation: ReductionsIndexRepresentation<Base.Index, Result>
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
_ representation: ReductionsIndexRepresentation<Base.Index, Result>
|
||||
) {
|
||||
self.representation = representation
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.representation < rhs.representation
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index { Index(.start) }
|
||||
|
||||
@inlinable
|
||||
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.")
|
||||
}
|
||||
}
|
||||
|
||||
@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)
|
||||
case .end:
|
||||
fatalError("Cannot get index after end index.")
|
||||
}
|
||||
}
|
||||
|
||||
@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
|
||||
case let (.end, .base(index, _)):
|
||||
return base.distance(from: base.endIndex, to: index)
|
||||
case (.end, .end):
|
||||
return 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension ExclusiveReductions: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
extension ExclusiveReductions: LazyCollectionProtocol
|
||||
where Base: LazyCollectionProtocol {}
|
||||
|
||||
// MARK: - Inclusive Reductions
|
||||
|
||||
extension LazySequenceProtocol {
|
||||
|
||||
/// Returns a sequence containing the accumulated results of combining the
|
||||
/// elements of the sequence using the given closure.
|
||||
///
|
||||
/// This can be seen as applying the reduce function to each element and
|
||||
/// providing the initial value followed by these results as a sequence.
|
||||
///
|
||||
/// ```
|
||||
/// let runningTotal = [1, 2, 3, 4].lazy.reductions(+)
|
||||
/// print(Array(runningTotal))
|
||||
///
|
||||
/// // prints [1, 3, 6, 10]
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - 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)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
|
||||
/// Returns an array containing the accumulated results of combining the
|
||||
/// elements of the sequence using the given closure.
|
||||
///
|
||||
/// This can be seen as applying the reduce function to each element and
|
||||
/// providing the initial value followed by these results as a sequence.
|
||||
///
|
||||
/// ```
|
||||
/// let runningTotal = [1, 2, 3, 4].reductions(+)
|
||||
/// print(runningTotal)
|
||||
///
|
||||
/// // prints [1, 3, 6, 10]
|
||||
/// ```
|
||||
///
|
||||
/// When `reductions(_:)` is called, the following steps occur:
|
||||
///
|
||||
/// 1. The `transform` closure is called with the first and second elements
|
||||
/// of the sequence, appending the result to an array of results.
|
||||
/// 2. The closure is called again repeatedly with the updated accumulating
|
||||
/// result and the next element of the sequence, adding each result to the
|
||||
/// array.
|
||||
/// 3. When the sequence is exhausted, the results array is returned to the
|
||||
/// caller.
|
||||
///
|
||||
/// If the sequence has no elements, `transform` is never executed and
|
||||
/// an empty array is returned.
|
||||
///
|
||||
/// 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.
|
||||
/// - Returns: An array of the reduced elements.
|
||||
///
|
||||
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
|
||||
@inlinable
|
||||
public func reductions(
|
||||
_ transform: (Element, Element) throws -> Element
|
||||
) rethrows -> [Element] {
|
||||
var iterator = makeIterator()
|
||||
guard let initial = iterator.next() else { return [] }
|
||||
return try IteratorSequence(iterator).reductions(initial, transform)
|
||||
}
|
||||
}
|
||||
|
||||
public struct InclusiveReductions<Base: Sequence> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let transform: (Base.Element, Base.Element) -> Base.Element
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
base: Base,
|
||||
transform: @escaping (Base.Element, Base.Element) -> Base.Element
|
||||
) {
|
||||
self.base = base
|
||||
self.transform = transform
|
||||
}
|
||||
}
|
||||
|
||||
extension InclusiveReductions: Sequence {
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var iterator: Base.Iterator
|
||||
|
||||
@usableFromInline
|
||||
internal var element: Base.Element?
|
||||
|
||||
@usableFromInline
|
||||
internal let transform: (Base.Element, Base.Element) -> Base.Element
|
||||
|
||||
@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
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> Base.Element? {
|
||||
guard let previous = element else {
|
||||
element = iterator.next()
|
||||
return element
|
||||
}
|
||||
guard let next = iterator.next() else { return nil }
|
||||
element = transform(previous, next)
|
||||
return element
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(iterator: base.makeIterator(),
|
||||
transform: transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension InclusiveReductions: Collection where Base: Collection {
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
internal let representation: ReductionsIndexRepresentation<Base.Index, Base.Element>
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
_ representation: ReductionsIndexRepresentation<Base.Index, Base.Element>
|
||||
) {
|
||||
self.representation = representation
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.representation < rhs.representation
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
guard base.startIndex != base.endIndex else { return endIndex }
|
||||
return Index(.start)
|
||||
}
|
||||
|
||||
@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.")
|
||||
}
|
||||
}
|
||||
|
||||
@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])))
|
||||
}
|
||||
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.")
|
||||
}
|
||||
}
|
||||
|
||||
@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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension InclusiveReductions: LazySequenceProtocol
|
||||
where Base: LazySequenceProtocol {}
|
||||
|
||||
extension InclusiveReductions: LazyCollectionProtocol
|
||||
where Base: LazyCollectionProtocol {}
|
||||
|
||||
// MARK: - ReductionsIndexRepresentation
|
||||
|
||||
@usableFromInline
|
||||
enum ReductionsIndexRepresentation<BaseIndex: Comparable, Result> {
|
||||
case start
|
||||
case base(index: BaseIndex, result: Result)
|
||||
case end
|
||||
}
|
||||
|
||||
extension ReductionsIndexRepresentation: Equatable {
|
||||
@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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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> {
|
||||
reductions(initial, transform)
|
||||
}
|
||||
|
||||
@available(*, deprecated, message: "Use reductions(into:_:) instead.")
|
||||
@inlinable
|
||||
public func scan<Result>(
|
||||
into initial: Result,
|
||||
_ transform: @escaping (inout Result, Element) -> Void
|
||||
) -> ExclusiveReductions<Result, Self> {
|
||||
reductions(into: initial, transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
|
||||
@available(*, deprecated, message: "Use reductions(_:_:) instead.")
|
||||
@inlinable
|
||||
public func scan<Result>(
|
||||
_ initial: Result,
|
||||
_ transform: (Result, Element) throws -> Result
|
||||
) rethrows -> [Result] {
|
||||
try reductions(initial, transform)
|
||||
}
|
||||
|
||||
@available(*, deprecated, message: "Use reductions(into:_:) instead.")
|
||||
@inlinable
|
||||
public func scan<Result>(
|
||||
into initial: Result,
|
||||
_ transform: (inout Result, Element) throws -> Void
|
||||
) rethrows -> [Result] {
|
||||
try reductions(into: initial, transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension LazySequenceProtocol {
|
||||
|
||||
@available(*, deprecated, message: "Use reductions(_:) instead.")
|
||||
@inlinable
|
||||
public func scan(
|
||||
_ transform: @escaping (Element, Element) -> Element
|
||||
) -> InclusiveReductions<Self> {
|
||||
reductions(transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
|
||||
@available(*, deprecated, message: "Use reductions(_:) instead.")
|
||||
@inlinable
|
||||
public func scan(
|
||||
_ transform: (Element, Element) throws -> Element
|
||||
) rethrows -> [Element] {
|
||||
try reductions(transform)
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
///
|
||||
/// - Postcondition: For returned indices `(lower, upper)`:
|
||||
/// `lower == limit || upper == limit`
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
@discardableResult
|
||||
internal mutating func _reverse(
|
||||
subrange: Range<Index>, until limit: Index
|
||||
@@ -94,7 +94,7 @@ extension MutableCollection {
|
||||
/// - distance(from: lhs.lowerBound, to: p) == distance(from:
|
||||
/// rhs.lowerBound, to: q)
|
||||
/// - p == lhs.upperBound || q == rhs.upperBound
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal mutating func _swapNonemptySubrangePrefixes(
|
||||
_ lhs: Range<Index>, _ rhs: Range<Index>
|
||||
) -> (Index, Index) {
|
||||
|
||||
@@ -61,7 +61,7 @@ public struct StrideSequence<Base: Sequence>: Sequence {
|
||||
@usableFromInline
|
||||
internal let stride: Int
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(base: Base, stride: Int) {
|
||||
precondition(stride > 0, "striding must be greater than zero")
|
||||
self.base = base
|
||||
@@ -82,7 +82,7 @@ extension StrideSequence {
|
||||
@usableFromInline
|
||||
internal var striding: Bool = false
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(iterator: Base.Iterator, stride: Int) {
|
||||
self.iterator = iterator
|
||||
self.stride = stride
|
||||
@@ -122,7 +122,7 @@ public struct StrideCollection<Base: Collection> {
|
||||
@usableFromInline
|
||||
internal let stride: Int
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(base: Base, stride: Int) {
|
||||
precondition(stride > 0, "striding must be greater than zero")
|
||||
self.base = base
|
||||
@@ -190,7 +190,7 @@ extension StrideCollection: Collection {
|
||||
: offsetBackward(i, offsetBy: -n, limitedBy: limit)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal func offsetForward(
|
||||
_ i: Index,
|
||||
offsetBy n: Int,
|
||||
@@ -220,7 +220,7 @@ extension StrideCollection: Collection {
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal func offsetBackward(
|
||||
_ i: Index,
|
||||
offsetBy n: Int,
|
||||
@@ -269,4 +269,22 @@ extension StrideCollection: BidirectionalCollection
|
||||
}
|
||||
|
||||
extension StrideCollection: 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 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 {}
|
||||
@@ -45,7 +45,7 @@ extension Collection {
|
||||
/// be called again.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal func endOfPrefix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
@@ -71,7 +71,7 @@ extension BidirectionalCollection {
|
||||
/// be called again.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal func startOfSuffix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
|
||||
@@ -7,94 +7,6 @@
|
||||
//
|
||||
// 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 "
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - 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..<endIndex]
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// 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 "
|
||||
///
|
||||
/// - 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
|
||||
@_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 {
|
||||
@@ -117,132 +29,8 @@ extension BidirectionalCollection {
|
||||
public func trimming(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> SubSequence {
|
||||
return 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"
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - 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[startIndex..<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"
|
||||
///
|
||||
/// - 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
|
||||
@_disfavoredOverload
|
||||
public mutating func trim(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows {
|
||||
replaceSubrange(startIndex..<endIndex, with: 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"
|
||||
///
|
||||
/// - 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
|
||||
@_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"
|
||||
///
|
||||
/// - 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 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"
|
||||
///
|
||||
/// - 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 trimSuffix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows {
|
||||
self = try trimmingSuffix(while: predicate)
|
||||
let start = try endOfPrefix(while: predicate)
|
||||
let end = try self[start...].startOfSuffix(while: predicate)
|
||||
return self[start..<end]
|
||||
}
|
||||
}
|
||||
@@ -9,82 +9,25 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A sequence wrapper that leaves out duplicate elements of a base sequence.
|
||||
public struct Uniqued<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 Uniqued: Sequence {
|
||||
/// The iterator for a `Uniqued` sequence.
|
||||
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 Uniqued: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// uniqued()
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Sequence where Element: Hashable {
|
||||
/// Returns a sequence with only the unique elements of this sequence, in the
|
||||
/// Returns an array 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(Array(uniqued))
|
||||
/// print(uniqued)
|
||||
/// // Prints '["dog", "pig", "cat", "ox"]'
|
||||
///
|
||||
/// - Returns: A sequence with only the unique elements of this sequence.
|
||||
/// - Returns: An array with only the unique elements of this sequence.
|
||||
/// .
|
||||
/// - Complexity: O(1).
|
||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
||||
@inlinable
|
||||
public func uniqued() -> Uniqued<Self, Element> {
|
||||
Uniqued(base: self, projection: { $0 })
|
||||
public func uniqued() -> [Element] {
|
||||
uniqued(on: { $0 })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,7 +40,7 @@ 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"]'
|
||||
///
|
||||
@@ -124,21 +67,3 @@ 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
|
||||
) -> Uniqued<Self, Subject> {
|
||||
Uniqued(base: self, projection: projection)
|
||||
}
|
||||
}
|
||||
@@ -47,16 +47,13 @@ extension Collection {
|
||||
/// A collection wrapper that presents a sliding window over the elements of
|
||||
/// a collection.
|
||||
public struct Windows<Base: Collection> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let size: Int
|
||||
public let base: Base
|
||||
public let size: Int
|
||||
|
||||
@usableFromInline
|
||||
internal var firstUpperBound: Base.Index?
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(base: Base, size: Int) {
|
||||
precondition(size > 0, "Windows size must be greater than zero")
|
||||
self.base = base
|
||||
@@ -75,7 +72,7 @@ extension Windows: Collection {
|
||||
@usableFromInline
|
||||
internal var upperBound: Base.Index
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal init(lowerBound: Base.Index, upperBound: Base.Index) {
|
||||
self.lowerBound = lowerBound
|
||||
self.upperBound = upperBound
|
||||
@@ -153,21 +150,21 @@ extension Windows: Collection {
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
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
|
||||
@usableFromInline
|
||||
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
|
||||
@usableFromInline
|
||||
internal func offsetForward(
|
||||
_ i: Index, by distance: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
@@ -238,7 +235,7 @@ extension Windows: Collection {
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@usableFromInline
|
||||
internal func offsetBackward(
|
||||
_ i: Index, by distance: Int, limitedBy limit: Index
|
||||
) -> Index? {
|
||||
@@ -350,4 +347,6 @@ 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 {}
|
||||
@@ -0,0 +1,140 @@
|
||||
import Darwin
|
||||
import Algorithms
|
||||
|
||||
struct Benchmark {
|
||||
var name: String
|
||||
var `default`: Int
|
||||
var body: (Int) -> Int
|
||||
}
|
||||
|
||||
let benchmarks = [
|
||||
Benchmark(name: "chain", default: 100) { count in
|
||||
let x = String(repeating: "_", count: 10_000)
|
||||
.chained(with: String(repeating: "-", count: 10_000))
|
||||
.chained(with: "0")
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let i = x.firstIndex(of: "0")!
|
||||
let d = x.distance(from: x.startIndex, to: i)
|
||||
v &+= d
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "chunked", default: 1000) { count in
|
||||
let x = (1...1000).shuffled()
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let y = x.chunked(by: <=)
|
||||
v &+= y.count
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "lazy chunked", default: 1000) { count in
|
||||
let x = (1...1000).shuffled()
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let y = x.lazy.chunked(by: <=)
|
||||
v &+= y.count
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "combinations", default: 100) { count in
|
||||
let x = 1...30
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let y = x.combinations(ofCount: 4)
|
||||
let combo = y.first(where: { combo in combo.allSatisfy { $0.isMultiple(of: 2) }})!
|
||||
v &+= combo.reduce(0, +)
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "stable partition", default: 100) { count in
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
var x = Array(1...10000)
|
||||
let i = x.stablePartition(by: { $0.isMultiple(of: 3) })
|
||||
v &+= i
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "permutations", default: 10) { count in
|
||||
let x = 1...20
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let y = x.permutations(ofCount: 4)
|
||||
let perm = y.first(where: { perm in perm.allSatisfy { $0.isMultiple(of: 2) }})!
|
||||
v &+= perm.reduce(0, +)
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "product", default: 1000) { count in
|
||||
let x = product(1...100, "abcdefghijklmnopqrstuvwxyz")
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let i = x.firstIndex(where: { $0 == 77 && $1 == "m" })!
|
||||
let d = x.distance(from: x.startIndex, to: i)
|
||||
v &+= d
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "sample", default: 1000) { count in
|
||||
let x = 1...10000
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let r = x.randomSample(count: 20)
|
||||
v &+= r.reduce(0, +)
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "stable sample", default: 1000) { count in
|
||||
let x = 1...10000
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let r = x.randomStableSample(count: 20)
|
||||
v &+= r.reduce(0, +)
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "uniqued", default: 1000) { count in
|
||||
let x = repeatElement(1...1000, count: 1000)
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let r = x.uniqued()
|
||||
v &+= r.count
|
||||
}
|
||||
return v
|
||||
},
|
||||
]
|
||||
|
||||
func printChoices() -> Never {
|
||||
print(benchmarks.enumerated().map { "\($0): \($1.name)" }.joined(separator: "\n"))
|
||||
exit(0)
|
||||
}
|
||||
|
||||
if CommandLine.arguments.count <= 1 {
|
||||
printChoices()
|
||||
} else {
|
||||
guard let choice = Int(CommandLine.arguments[1]), benchmarks.indices.contains(choice) else {
|
||||
print("Invalid choice:")
|
||||
printChoices()
|
||||
}
|
||||
|
||||
let bench = benchmarks[choice]
|
||||
let count: Int
|
||||
if CommandLine.arguments.count > 2, let c = Int(CommandLine.arguments[2]) {
|
||||
count = c
|
||||
} else {
|
||||
count = bench.default
|
||||
}
|
||||
|
||||
print(bench.body(count))
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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() {
|
||||
validateIndexTraversals(
|
||||
(0..<0).adjacentPairs(),
|
||||
(0..<1).adjacentPairs(),
|
||||
(0..<2).adjacentPairs(),
|
||||
(0..<5).adjacentPairs())
|
||||
}
|
||||
|
||||
func testLaziness() {
|
||||
XCTAssertLazySequence((0...).lazy.adjacentPairs())
|
||||
XCTAssertLazyCollection((0..<100).lazy.adjacentPairs())
|
||||
}
|
||||
}
|
||||
@@ -47,12 +47,8 @@ final class ChunkedTests: XCTestCase {
|
||||
func testSimple() {
|
||||
// Example
|
||||
let names = ["David", "Kyle", "Karoy", "Nate"]
|
||||
let chunks = names.chunked(on: { $0.first! })
|
||||
let expected: [(Character, ArraySlice<String>)] = [
|
||||
("D", ["David"]),
|
||||
("K", ["Kyle", "Karoy"]),
|
||||
("N", ["Nate"])]
|
||||
XCTAssertEqualSequences(expected, chunks, by: ==)
|
||||
let chunks = names.chunked(on: { $0.first })
|
||||
XCTAssertEqualSequences([["David"], ["Kyle", "Karoy"], ["Nate"]], chunks)
|
||||
|
||||
// Empty sequence
|
||||
XCTAssertEqual(0, names.prefix(0).chunked(on: { $0.first }).count)
|
||||
@@ -63,11 +59,10 @@ final class ChunkedTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testChunkedOn() {
|
||||
validateFruitChunks(fruits.chunked(on: { $0.first }).map { $1 })
|
||||
validateFruitChunks(fruits.chunked(on: { $0.first }))
|
||||
|
||||
let lazyChunks = fruits.lazy.chunked(on: { $0.first })
|
||||
validateFruitChunks(lazyChunks.map { $1 })
|
||||
validateIndexTraversals(lazyChunks)
|
||||
validateFruitChunks(lazyChunks)
|
||||
}
|
||||
|
||||
func testChunkedBy() {
|
||||
@@ -75,7 +70,6 @@ final class ChunkedTests: XCTestCase {
|
||||
|
||||
let lazyChunks = fruits.lazy.chunked(by: { $0.first == $1.first })
|
||||
validateFruitChunks(lazyChunks)
|
||||
validateIndexTraversals(lazyChunks)
|
||||
}
|
||||
|
||||
func testChunkedLazy() {
|
||||
@@ -83,10 +77,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), [])
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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() {
|
||||
for array in self.tests {
|
||||
validateIndexTraversals(array.compacted())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,70 +19,28 @@ 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 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)
|
||||
|
||||
func testCycleLazy() {
|
||||
XCTAssertLazySequence((1...4).lazy.cycled())
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
@testable import Algorithms
|
||||
import Algorithms
|
||||
|
||||
final class IntersperseTests: XCTestCase {
|
||||
func testSequence() {
|
||||
@@ -62,31 +62,4 @@ final class IntersperseTests: XCTestCase {
|
||||
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() {
|
||||
validateIndexTraversals(
|
||||
(0..<0).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }),
|
||||
(0..<1).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }),
|
||||
(0..<2).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }),
|
||||
(0..<5).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }))
|
||||
}
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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() {
|
||||
// the last test case takes too long to run
|
||||
for strings in stringArrays.dropLast() {
|
||||
validateIndexTraversals(strings.joined() as FlattenCollection)
|
||||
validateIndexTraversals(strings.joined(by: ", "))
|
||||
}
|
||||
|
||||
for (strings, separator) in product(stringArrays.dropLast(), ["", " ", ", "]) {
|
||||
validateIndexTraversals(strings.joined(by: separator))
|
||||
validateIndexTraversals(strings.lazy.joined(by: { _, _ in separator }))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -185,90 +185,3 @@ 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Algorithms
|
||||
|
||||
final class ReductionsTests: XCTestCase {
|
||||
|
||||
struct TestError: Error {}
|
||||
|
||||
// MARK: - Exclusive Reductions
|
||||
|
||||
func testExclusiveLazy() {
|
||||
XCTAssertEqualSequences((1...).prefix(4).lazy.reductions(0, +), [0, 1, 3, 6, 10])
|
||||
XCTAssertEqualSequences((1...).prefix(1).lazy.reductions(0, +), [0, 1])
|
||||
XCTAssertEqualSequences((1...).prefix(0).lazy.reductions(0, +), [0])
|
||||
|
||||
XCTAssertEqualCollections([1, 2, 3, 4].lazy.reductions(0, +), [0, 1, 3, 6, 10])
|
||||
XCTAssertEqualCollections([1].lazy.reductions(0, +), [0, 1])
|
||||
XCTAssertEqualCollections(EmptyCollection<Int>().lazy.reductions(0, +), [0])
|
||||
|
||||
XCTAssertEqual([1, 2, 3, 4].lazy.reductions(into: 0, +=), [0, 1, 3, 6, 10])
|
||||
|
||||
XCTAssertEqual([1].lazy.reductions(into: 0, +=), [0, 1])
|
||||
|
||||
XCTAssertEqual(EmptyCollection<Int>().lazy.reductions(into: 0, +=), [0])
|
||||
|
||||
XCTAssertLazySequence((1...).prefix(1).lazy.reductions(0, +))
|
||||
XCTAssertLazySequence([1].lazy.reductions(0, +))
|
||||
XCTAssertLazyCollection([1].lazy.reductions(0, +))
|
||||
}
|
||||
|
||||
func testExclusiveEager() {
|
||||
XCTAssertEqual([1, 2, 3, 4].reductions(0, +), [0, 1, 3, 6, 10])
|
||||
XCTAssertEqual([1].reductions(0, +), [0, 1])
|
||||
XCTAssertEqual(EmptyCollection<Int>().reductions(0, +), [0])
|
||||
|
||||
XCTAssertEqual([1, 2, 3, 4].reductions(into: 0, +=), [0, 1, 3, 6, 10])
|
||||
|
||||
XCTAssertEqual([1].reductions(into: 0, +=), [0, 1])
|
||||
|
||||
XCTAssertEqual(EmptyCollection<Int>().reductions(into: 0, +=), [0])
|
||||
|
||||
XCTAssertNoThrow(try [].reductions(0) { _, _ in throw TestError() })
|
||||
XCTAssertThrowsError(try [1].reductions(0) { _, _ in throw TestError() })
|
||||
}
|
||||
|
||||
// MARK: - Inclusive Reductions
|
||||
|
||||
func testInclusiveLazy() {
|
||||
XCTAssertEqualSequences((1...).prefix(4).lazy.reductions(+), [1, 3, 6, 10])
|
||||
XCTAssertEqualSequences((1...).prefix(1).lazy.reductions(+), [1])
|
||||
XCTAssertEqualSequences((1...).prefix(0).lazy.reductions(+), [])
|
||||
|
||||
XCTAssertEqualCollections([1, 2, 3, 4].lazy.reductions(+), [1, 3, 6, 10])
|
||||
XCTAssertEqualCollections([1].lazy.reductions(+), [1])
|
||||
XCTAssertEqualCollections(EmptyCollection<Int>().lazy.reductions(+), [])
|
||||
|
||||
XCTAssertLazySequence((1...).prefix(1).lazy.reductions(+))
|
||||
XCTAssertLazySequence([1].lazy.reductions(+))
|
||||
XCTAssertLazyCollection([1].lazy.reductions(+))
|
||||
}
|
||||
|
||||
func testInclusiveEager() {
|
||||
XCTAssertEqual([1, 2, 3, 4].reductions(+), [1, 3, 6, 10])
|
||||
XCTAssertEqual([1].reductions(+), [1])
|
||||
XCTAssertEqual(EmptyCollection<Int>().reductions(+), [])
|
||||
|
||||
XCTAssertNoThrow(try [].reductions { _, _ in throw TestError() })
|
||||
XCTAssertNoThrow(try [1].reductions { _, _ in throw TestError() })
|
||||
XCTAssertThrowsError(try [1, 1].reductions { _, _ in throw TestError() })
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,19 @@ 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
|
||||
|
||||
@@ -148,21 +148,6 @@ func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
|
||||
func XCTAssertLazySequence<S: LazySequenceProtocol>(_: S) {}
|
||||
func XCTAssertLazyCollection<S: LazyCollectionProtocol>(_: S) {}
|
||||
|
||||
/// Asserts two collections are equal by using their indices to access elements.
|
||||
func XCTAssertEqualCollections<C1: Collection, C2: Collection>(
|
||||
_ expression1: @autoclosure () throws -> C1,
|
||||
_ expression2: @autoclosure () throws -> C2,
|
||||
_ message: @autoclosure () -> String = "",
|
||||
file: StaticString = #file, line: UInt = #line
|
||||
) rethrows where C1.Element: Equatable, C1.Element == C2.Element {
|
||||
let c1 = try expression1()
|
||||
let c2 = try expression2()
|
||||
XCTAssertEqual(c1.indices.count, c2.indices.count, message(), file: file, line: line)
|
||||
for index in zip(c1.indices, c2.indices) {
|
||||
XCTAssertEqual(c1[index.0], c2[index.1], message(), file: file, line: line)
|
||||
}
|
||||
}
|
||||
|
||||
/// Tests that all index traversal methods behave as expected.
|
||||
///
|
||||
/// Verifies the correctness of the implementations of `startIndex`, `endIndex`,
|
||||
|
||||
@@ -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,83 +26,34 @@ 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])
|
||||
}
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Algorithms
|
||||
|
||||
final class UniquePermutationsTests: XCTestCase {
|
||||
static let numbers = [1, 1, 1, 2, 3]
|
||||
|
||||
static let numbersPermutations: [[[Int]]] = [
|
||||
// k = 0
|
||||
[[]],
|
||||
// 1
|
||||
[[1], [2], [3]],
|
||||
// 2
|
||||
[[1, 1], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]],
|
||||
// 3
|
||||
[[1, 1, 1], [1, 1, 2], [1, 1, 3],
|
||||
[1, 2, 1], [1, 2, 3], [1, 3, 1], [1, 3, 2],
|
||||
[2, 1, 1], [2, 1, 3], [2, 3, 1],
|
||||
[3, 1, 1], [3, 1, 2], [3, 2, 1]],
|
||||
// 4
|
||||
[[1, 1, 1, 2], [1, 1, 1, 3],
|
||||
[1, 1, 2, 1], [1, 1, 2, 3],
|
||||
[1, 1, 3, 1], [1, 1, 3, 2],
|
||||
[1, 2, 1, 1], [1, 2, 1, 3], [1, 2, 3, 1],
|
||||
[1, 3, 1, 1], [1, 3, 1, 2], [1, 3, 2, 1],
|
||||
[2, 1, 1, 1], [2, 1, 1, 3], [2, 1, 3, 1], [2, 3, 1, 1],
|
||||
[3, 1, 1, 1], [3, 1, 1, 2], [3, 1, 2, 1], [3, 2, 1, 1]],
|
||||
// 5
|
||||
[[1, 1, 1, 2, 3], [1, 1, 1, 3, 2],
|
||||
[1, 1, 2, 1, 3], [1, 1, 2, 3, 1],
|
||||
[1, 1, 3, 1, 2], [1, 1, 3, 2, 1],
|
||||
[1, 2, 1, 1, 3], [1, 2, 1, 3, 1], [1, 2, 3, 1, 1],
|
||||
[1, 3, 1, 1, 2], [1, 3, 1, 2, 1], [1, 3, 2, 1, 1],
|
||||
[2, 1, 1, 1, 3], [2, 1, 1, 3, 1], [2, 1, 3, 1, 1], [2, 3, 1, 1, 1],
|
||||
[3, 1, 1, 1, 2], [3, 1, 1, 2, 1], [3, 1, 2, 1, 1], [3, 2, 1, 1, 1]]
|
||||
]
|
||||
}
|
||||
|
||||
extension UniquePermutationsTests {
|
||||
func testEmpty() {
|
||||
XCTAssertEqualSequences(([] as [Int]).uniquePermutations(), [[]])
|
||||
XCTAssertEqualSequences(([] as [Int]).uniquePermutations(ofCount: 0), [[]])
|
||||
XCTAssertEqualSequences(([] as [Int]).uniquePermutations(ofCount: 1), [])
|
||||
XCTAssertEqualSequences(
|
||||
([] as [Int]).uniquePermutations(ofCount: 1...3), [])
|
||||
}
|
||||
|
||||
func testSingleCounts() {
|
||||
for (k, expectation) in Self.numbersPermutations.enumerated() {
|
||||
XCTAssertEqualSequences(
|
||||
expectation,
|
||||
Self.numbers.uniquePermutations(ofCount: k))
|
||||
}
|
||||
|
||||
XCTAssertEqualSequences(
|
||||
Self.numbersPermutations[5],
|
||||
Self.numbers.uniquePermutations())
|
||||
}
|
||||
|
||||
func testRanges() {
|
||||
for lower in Self.numbersPermutations.indices {
|
||||
// upper bounded
|
||||
XCTAssertEqualSequences(
|
||||
Self.numbersPermutations[...lower].joined(),
|
||||
Self.numbers.uniquePermutations(ofCount: ...lower))
|
||||
|
||||
// lower bounded
|
||||
XCTAssertEqualSequences(
|
||||
Self.numbersPermutations[lower...].joined(),
|
||||
Self.numbers.uniquePermutations(ofCount: lower...))
|
||||
|
||||
for upper in lower..<Self.numbersPermutations.count {
|
||||
XCTAssertEqualSequences(
|
||||
Self.numbersPermutations[lower..<upper].joined(),
|
||||
Self.numbers.uniquePermutations(ofCount: lower..<upper))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension UniquePermutationsTests {
|
||||
private final class IntBox: Hashable {
|
||||
var value: Int
|
||||
|
||||
init(_ value: Int) {
|
||||
self.value = value
|
||||
}
|
||||
|
||||
static func == (lhs: IntBox, rhs: IntBox) -> Bool {
|
||||
lhs.value == rhs.value
|
||||
}
|
||||
|
||||
func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(value)
|
||||
}
|
||||
}
|
||||
|
||||
func testFirstUnique() {
|
||||
// When duplicate elements are encountered, all permutations use the first
|
||||
// instance of the duplicated elements.
|
||||
let numbers = Self.numbers.map(IntBox.init)
|
||||
for k in 0...numbers.count {
|
||||
for p in numbers.uniquePermutations(ofCount: k) {
|
||||
XCTAssertTrue(p.filter { $0.value == 1 }.allSatisfy { $0 === numbers[0] })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testLaziness() {
|
||||
XCTAssertLazySequence("ABCD".lazy.uniquePermutations())
|
||||
}
|
||||
}
|
||||
@@ -17,13 +17,10 @@ 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, Array(b).count)
|
||||
XCTAssertEqual(10, b.count)
|
||||
|
||||
let c: [Int] = []
|
||||
XCTAssertEqualSequences(c.uniqued(), [])
|
||||
|
||||
let d = Array(repeating: 1, count: 10)
|
||||
XCTAssertEqualSequences(d.uniqued(), [1])
|
||||
XCTAssertEqual(c.uniqued(), [])
|
||||
}
|
||||
|
||||
func testUniqueOn() {
|
||||
@@ -33,21 +30,5 @@ 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"])
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user