mirror of
https://github.com/apple/swift-algorithms
synced 2026-11-22 04:10:39 +00:00
Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0bd7f4dcb1 | ||
|
|
34eec0dd27 | ||
|
|
09dc5e4354 | ||
|
|
0a01f21eae | ||
|
|
34b1705efd | ||
|
|
ae92f2b33f | ||
|
|
33abb69428 | ||
|
|
82ee335a48 | ||
|
|
9e3900be49 | ||
|
|
9dd88e5eaf | ||
|
|
c3b3acbca3 | ||
|
|
f6919dfc30 | ||
|
|
f2fd047eed | ||
|
|
5c54f200e7 | ||
|
|
2e71e228c0 | ||
|
|
328631d60c | ||
|
|
0ebed148c2 | ||
|
|
c8ae549e42 | ||
|
|
dd4e0e70ff |
No files matched your search
+36
-2
@@ -10,9 +10,35 @@ This project follows semantic versioning.
|
||||
|
||||
*No new changes.*
|
||||
|
||||
## [1.2.0] - 2023-11-14
|
||||
|
||||
### Additions
|
||||
|
||||
- Sequences have new `grouped(by:)` and `keyed(by:)` methods, which simplify
|
||||
building dictionaries based on sequence elements: ([#197])
|
||||
|
||||
```swift
|
||||
let evensOdds = (1...10).grouped(by: { $0.isMultiple(of: 2) ? "even" : "odd" })
|
||||
// ["even": [2, 4, 6, 8, 10], "odd": [1, 3, 5, 7, 9]]
|
||||
|
||||
let animals = ["Aardvark", "Alpaca", "Armadillo", "Barracuda", "Buffalo", ...]
|
||||
let alphaAnimals = animals.keyed(by: \.first!, resolvingConflictsWith: { _, first, _ in first })
|
||||
// ["A": "Aardvark", "B": "Barracuda", ...]
|
||||
```
|
||||
- The `endOfPrefix(while:)` and `startOfSuffix(while)` methods are now public.
|
||||
These methods were previously implementation details of the `trimming` group
|
||||
of methods. ([#211])
|
||||
|
||||
### Fixes
|
||||
|
||||
- Documentation and performance improvements. ([#202], [#210])
|
||||
|
||||
The 1.2.0 release includes contributions from [amomchilov], [mattyoung], [natecook1000], [stephentyrone], and [ttsugriy].
|
||||
Thank you!
|
||||
|
||||
---
|
||||
|
||||
## [1.1.0] - 2023-08-24
|
||||
## [1.1.0] - 2023-10-05
|
||||
|
||||
### Additions
|
||||
|
||||
@@ -312,7 +338,8 @@ 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/1.1.0...HEAD
|
||||
[Unreleased]: https://github.com/apple/swift-algorithms/compare/1.2.0...HEAD
|
||||
[1.2.0]: https://github.com/apple/swift-algorithms/compare/1.1.0...1.2.0
|
||||
[1.1.0]: https://github.com/apple/swift-algorithms/compare/1.0.0...1.1.0
|
||||
[1.0.0]: https://github.com/apple/swift-algorithms/compare/0.2.1...1.0.0
|
||||
[0.2.1]: https://github.com/apple/swift-algorithms/compare/0.2.0...0.2.1
|
||||
@@ -354,9 +381,14 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
|
||||
[#138]: https://github.com/apple/swift-algorithms/pull/138
|
||||
[#152]: https://github.com/apple/swift-algorithms/pull/152
|
||||
[#162]: https://github.com/apple/swift-algorithms/pull/162
|
||||
[#197]: https://github.com/apple/swift-algorithms/pull/197
|
||||
[#202]: https://github.com/apple/swift-algorithms/pull/202
|
||||
[#210]: https://github.com/apple/swift-algorithms/pull/210
|
||||
[#211]: https://github.com/apple/swift-algorithms/pull/211
|
||||
|
||||
<!-- Link references for contributors -->
|
||||
|
||||
[amomchilov]: https://github.com/apple/swift-algorithms/commits?author=amomchilov
|
||||
[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
|
||||
@@ -376,6 +408,7 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
|
||||
[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
|
||||
[mattyoung]: https://github.com/apple/swift-algorithms/commits?author=mattyoung
|
||||
[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
|
||||
@@ -393,3 +426,4 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
|
||||
[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
|
||||
[ttsugriy]: https://github.com/apple/swift-algorithms/commits?author=ttsugriy
|
||||
@@ -5,9 +5,6 @@
|
||||
|
||||
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()
|
||||
|
||||
@@ -86,7 +86,7 @@ call to `CombinationsSequence.Iterator.next()` is an O(_n_) operation.
|
||||
### Naming
|
||||
|
||||
The parameter label in `combination(ofCount:)` is the best match for the
|
||||
Swift API guidelines. A few other options were considered:
|
||||
[Swift's API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/). A few other options were considered:
|
||||
|
||||
- When the standard library uses `of` as a label, the parameter is generally
|
||||
the object of the operation, as in `type(of:)` and `firstIndex(of:)`, and
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
# Grouped
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Grouped.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/GroupedTests.swift)]
|
||||
|
||||
Groups up elements of a sequence into a new Dictionary, whose values are Arrays of grouped elements, each keyed by the result of the given closure.
|
||||
|
||||
```swift
|
||||
let fruits = ["Apricot", "Banana", "Apple", "Cherry", "Avocado", "Coconut"]
|
||||
let fruitsByLetter = fruits.grouped(by: { $0.first! })
|
||||
// Results in:
|
||||
// [
|
||||
// "B": ["Banana"],
|
||||
// "A": ["Apricot", "Apple", "Avocado"],
|
||||
// "C": ["Cherry", "Coconut"],
|
||||
// ]
|
||||
```
|
||||
|
||||
If you wish to achieve a similar effect but for single values (instead of Arrays of grouped values), see [`keyed(by:)`](Keyed.md).
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The `grouped(by:)` method is declared as a `Sequence` extension returning
|
||||
`[GroupKey: [Element]]`.
|
||||
|
||||
```swift
|
||||
extension Sequence {
|
||||
public func grouped<GroupKey>(
|
||||
by keyForValue: (Element) throws -> GroupKey
|
||||
) rethrows -> [GroupKey: [Element]]
|
||||
}
|
||||
```
|
||||
|
||||
### Complexity
|
||||
|
||||
Calling `grouped(by:)` is an O(_n_) operation.
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
| Language | Grouping API |
|
||||
|---------------|--------------|
|
||||
| Java | [`groupingBy`](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/util/stream/Collectors.html#groupingBy(java.util.function.Function)) |
|
||||
| Kotlin | [`groupBy`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/group-by.html) |
|
||||
| C# | [`GroupBy`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.groupby?view=net-7.0#system-linq-enumerable-groupby) |
|
||||
| Rust | [`group_by`](https://doc.rust-lang.org/std/primitive.slice.html#method.group_by) |
|
||||
| Ruby | [`group_by`](https://ruby-doc.org/3.2.2/Enumerable.html#method-i-group_by) |
|
||||
| Python | [`groupby`](https://docs.python.org/3/library/itertools.html#itertools.groupby) |
|
||||
| PHP (Laravel) | [`groupBy`](https://laravel.com/docs/10.x/collections#method-groupby) |
|
||||
|
||||
#### Naming
|
||||
|
||||
All the surveyed languages name this operation with a variant of "grouped" or "grouping". The past tense `grouped(by:)` best fits [Swift's API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/).
|
||||
|
||||
#### Customization points
|
||||
|
||||
Java and C# are interesting in that they provide multiple overloads with several points of customization:
|
||||
|
||||
1. Changing the type of the groups.
|
||||
1. E.g. the groups can be Sets instead of Arrays.
|
||||
1. Akin to calling `.transformValues { group in Set(group) }` on the resultant dictionary, but avoiding the intermediate allocation of Arrays of each group.
|
||||
2. Picking which elements end up in the groupings.
|
||||
1. The default is the elements of the input sequence, but can be changed.
|
||||
2. Akin to calling `.transformValues { group in group.map(someTransform) }` on the resultant dictionary, but avoiding the intermediate allocation of Arrays of each group.
|
||||
3. Changing the type of the outermost collection.
|
||||
1. E.g using an `OrderedDictionary`, `SortedDictionary` or `TreeDictionary` instead of the default (hashed, unordered) `Dictionary`.
|
||||
2. There's no great way to achieve this with the `grouped(by:)`. One could wrap the resultant dictionary in an initializer to one of the other dictionary types, but that isn't sufficient: Once the `Dictionary` loses the ordering, there's no way to get it back when constructing one of the ordered dictionary variants.
|
||||
|
||||
It is not clear which of these points of customization are worth supporting, or what the best way to express them might be.
|
||||
@@ -0,0 +1,78 @@
|
||||
# Keyed
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Keyed.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/KeyedTests.swift)]
|
||||
|
||||
Stores the elements of a sequence as the values of a Dictionary, keyed by the result of the given closure.
|
||||
|
||||
```swift
|
||||
let fruits = ["Apricot", "Banana", "Apple", "Cherry", "Blackberry", "Avocado", "Coconut"]
|
||||
let fruitByLetter = fruits.keyed(by: { $0.first! })
|
||||
// Results in:
|
||||
// [
|
||||
// "A": "Avocado",
|
||||
// "B": "Blackberry",
|
||||
// "C": "Coconut",
|
||||
// ]
|
||||
```
|
||||
|
||||
On a key-collision, the latest element is kept by default. Alternatively, you can provide a closure which specifies which value to keep:
|
||||
|
||||
```swift
|
||||
let fruits = ["Apricot", "Banana", "Apple", "Cherry", "Blackberry", "Avocado", "Coconut"]
|
||||
let fruitsByLetter = fruits.keyed(
|
||||
by: { $0.first! },
|
||||
resolvingConflictsWith: { key, old, new in old } // Always pick the first fruit
|
||||
)
|
||||
// Results in:
|
||||
// [
|
||||
// "A": "Apricot",
|
||||
// "B": "Banana",
|
||||
// "C": "Cherry",
|
||||
// ]
|
||||
```
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The `keyed(by:)` and `keyed(by:resolvingConflictsWith:)` methods are declared in an `Sequence` extension, both returning `[Key: Element]`.
|
||||
|
||||
```swift
|
||||
extension Sequence {
|
||||
public func keyed<Key>(
|
||||
by keyForValue: (Element) throws -> Key
|
||||
) rethrows -> [Key: Element]
|
||||
|
||||
public func keyed<Key>(
|
||||
by keyForValue: (Element) throws -> Key,
|
||||
resolvingConflictsWith resolve: ((Key, Element, Element) throws -> Element)? = nil
|
||||
) rethrows -> [Key: Element]
|
||||
}
|
||||
```
|
||||
|
||||
### Complexity
|
||||
|
||||
Calling `keyed(by:)` is an O(_n_) operation.
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
| Language | "Keying" API |
|
||||
|---------------|-------------|
|
||||
| Java | [`toMap`](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/util/stream/Collectors.html#toMap(java.util.function.Function,java.util.function.Function)) |
|
||||
| Kotlin | [`associatedBy`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/associate-by.html) |
|
||||
| C# | [`ToDictionary`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.todictionary?view=net-7.0#system-linq-enumerable-todictionary) |
|
||||
| Ruby (ActiveSupport) | [`index_by`](https://rubydoc.info/gems/activesupport/7.0.5/Enumerable#index_by-instance_method) |
|
||||
| PHP (Laravel) | [`keyBy`](https://laravel.com/docs/10.x/collections#method-keyby) |
|
||||
|
||||
#### Rejected alternative names
|
||||
|
||||
1. Java's `toMap` is referring to `Map`/`HashMap`, their naming for Dictionaries and other associative collections. It's easy to confuse with the transformation function, `Sequence.map(_:)`.
|
||||
2. C#'s `toXXX()` naming doesn't suite Swift well, which tends to prefer `Foo.init` over `toFoo()` methods.
|
||||
3. Ruby's `index_by` naming doesn't fit Swift well, where "index" is a specific term (e.g. the `associatedtype Index` on `Collection`). There is also a [`index(by:)`](Index.md) method in swift-algorithms, is specifically to do with matching elements up with their indices, and not any arbitrary derived value.
|
||||
|
||||
#### Alternative names
|
||||
|
||||
Kotlin's `associatedBy` naming is a good alternative, and matches the past tense of [Swift's API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/), though perhaps we'd spell it `associated(by:)`.
|
||||
|
||||
#### Customization points
|
||||
|
||||
Java and C# are interesting in that they provide overloads that let you customize the type of the outermost collection. E.g. using an `OrderedDictionary` instead of the default (hashed, unordered) `Dictionary`.
|
||||
@@ -0,0 +1,53 @@
|
||||
# Guides
|
||||
|
||||
These guides describe the design and intention behind the APIs included in the `Algorithms` library. For further reading, see the [announcement on swift.org](https://swift.org/blog/swift-algorithms/) and the [official documentation](https://swiftpackageindex.com/apple/swift-algorithms/documentation/algorithms).
|
||||
|
||||
## Contents
|
||||
|
||||
#### Combinations / permutations
|
||||
|
||||
- [`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
|
||||
|
||||
- [`rotate(toStartAt:)`, `rotate(subrange:toStartAt:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Rotate.md): In-place rotation of elements.
|
||||
- [`stablePartition(by:)`, `stablePartition(subrange:by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Partition.md): A partition that preserves the relative order of the resulting prefix and suffix.
|
||||
|
||||
#### 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.
|
||||
|
||||
#### Subsetting operations
|
||||
|
||||
- [`compacted()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Compacted.md): Drops the `nil`s from a sequence or collection, unwrapping the remaining elements.
|
||||
- [`partitioned(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Partition.md): Returns the elements in a sequence or collection that do and do not match a given predicate.
|
||||
- [`randomSample(count:)`, `randomSample(count:using:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/RandomSampling.md): Randomly selects a specific number of elements from a collection.
|
||||
- [`randomStableSample(count:)`, `randomStableSample(count:using:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/RandomSampling.md): Randomly selects a specific number of elements from a collection, preserving their original relative order.
|
||||
- [`striding(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Stride.md): Returns every nth element of a collection.
|
||||
- [`suffix(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Suffix.md): Returns the suffix of a collection where all element pass a given predicate.
|
||||
- [`trimmingPrefix(while:)`, `trimmingSuffix(while)`, `trimming(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Trim.md): Returns a slice by trimming elements from a collection's start, end, or both. The mutating `trim...` methods trim a collection in place.
|
||||
- [`uniqued()`, `uniqued(on:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Unique.md): The unique elements of a collection, preserving their order.
|
||||
- [`minAndMax()`, `minAndMax(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/MinMax.md): Returns the smallest and largest elements of a sequence.
|
||||
|
||||
#### Partial sorting
|
||||
|
||||
- [`min(count:)`, `max(count:)`, `min(count:sortedBy:)`, `max(count:sortedBy:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/MinMax.md): Returns the smallest or largest elements of a collection, sorted by a predicate.
|
||||
|
||||
#### 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.
|
||||
- [`grouped(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Grouped.md): Group up elements using the given closure, returning a Dictionary of those groups, keyed by the results of the closure.
|
||||
- [`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.
|
||||
- [`keyed(by:)`, `keyed(by:resolvingConflictsBy:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Keyed.md): Returns a Dictionary that associates elements of a sequence with the keys returned by the given closure.
|
||||
- [`partitioningIndex(where:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Partition.md): Returns the starting index of the partition of a collection that matches a predicate.
|
||||
- [`reductions(_:)`, `reductions(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Reductions.md): Returns all the intermediate states of reducing the elements of a sequence or collection.
|
||||
- [`split(maxSplits:omittingEmptySubsequences:whereSeparator)`, `split(separator:maxSplits:omittingEmptySubsequences)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Split.md): Lazy versions of the Standard Library's eager operations that split sequences and collections into subsequences separated by the specified separator element.
|
||||
- [`windows(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Windows.md): Breaks a collection into overlapping subsequences where elements are slices from the original collection.
|
||||
+1
-1
@@ -9,7 +9,7 @@ collection until predicate returns `false` and skipping the remaining elements.
|
||||
This example uses `suffix(while: )` to iterate through collection of integers
|
||||
from the end until the predicate returns false, in this case when `$0 <= 5`
|
||||
```swift
|
||||
(0...10).suffix(while: { $0 > 5 } // == [6,7,8,9,10]
|
||||
(0...10).suffix(while: { $0 > 5 }) // == [6,7,8,9,10]
|
||||
```
|
||||
|
||||
## Detailed Design
|
||||
|
||||
+50
-29
@@ -3,8 +3,8 @@
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Trim.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/TrimTests.swift)]
|
||||
|
||||
Returns a `SubSequence` formed by discarding all elements at the start and end
|
||||
of the collection which satisfy the given predicate.
|
||||
A group of methods that return the `SubSequence` formed by discarding elements
|
||||
at the start and/or end of the collection which satisfy the given predicate.
|
||||
|
||||
This example uses `trimming(while:)` to get a substring without the white space
|
||||
at the beginning and end of the string.
|
||||
@@ -17,24 +17,44 @@ let results = [2, 10, 11, 15, 20, 21, 100].trimming(while: { $0.isMultiple(of: 2
|
||||
print(results) // [11, 15, 20, 21]
|
||||
```
|
||||
|
||||
The `Algorithms` library also includes methods that trim from each end,
|
||||
as well as mutating versions of all three methods.
|
||||
|
||||
## Detailed Design
|
||||
|
||||
A new method is added to `BidirectionalCollection`:
|
||||
New methods are added to `Collection` and `BidirectionalCollection`:
|
||||
|
||||
```swift
|
||||
extension Collection {
|
||||
func trimmingPrefix(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
|
||||
}
|
||||
|
||||
extension BidirectionalCollection {
|
||||
public func trimming(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
|
||||
func trimmingSuffix(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
|
||||
|
||||
func trimming(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
|
||||
}
|
||||
|
||||
extension Collection where Self: RangeReplaceableCollection {
|
||||
mutating func trimPrefix(while predicate: (Element) throws -> Bool) rethrows
|
||||
}
|
||||
|
||||
extension BidirectionalCollection where Self: RangeReplaceableCollection {
|
||||
mutating func trimSuffix(while predicate: (Element) throws -> Bool) rethrows
|
||||
|
||||
mutating func trim(while predicate: (Element) throws -> Bool) rethrows
|
||||
}
|
||||
```
|
||||
|
||||
This method requires `BidirectionalCollection` for an efficient implementation
|
||||
which visits as few elements as possible.
|
||||
There are also overloads of the mutating methods when `Self == Self.SubSequence`,
|
||||
for non-range-replaceable self-slicing types.
|
||||
|
||||
A less-efficient implementation is _possible_ for any `Collection`, which would
|
||||
involve always traversing the entire collection. This implementation is not
|
||||
provided, as it would mean developers of generic algorithms who forget to add
|
||||
the `BidirectionalCollection` constraint will receive that inefficient
|
||||
implementation:
|
||||
Though the `trimming` and `trimmingSuffix` methods are declared on
|
||||
`BidirectionalCollection`, a less-efficient implementation is _possible_ for
|
||||
any `Collection`, which would involve always traversing the entire collection.
|
||||
This implementation is not provided, as it would mean developers of generic
|
||||
algorithms who forget to add the `BidirectionalCollection` constraint will
|
||||
receive that inefficient implementation:
|
||||
|
||||
```swift
|
||||
func myAlgorithm<Input>(input: Input) where Input: Collection {
|
||||
@@ -50,28 +70,29 @@ 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
|
||||
#### Supporting Methods
|
||||
|
||||
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.
|
||||
The `endOfPrefix(while:)` and `startOfSuffix(while:)` methods are used
|
||||
in the implementation of the trimming methods described above. As these
|
||||
supporting methods are independently useful, they are included in the library
|
||||
as well.
|
||||
|
||||
```swift
|
||||
let myString = " hello, world "
|
||||
print(myString.trimmingPrefix(while: \.isWhitespace)) // "hello, world "
|
||||
extension Collection {
|
||||
/// Returns the exclusive upper bound of the prefix of elements that satisfy
|
||||
/// the predicate.
|
||||
func endOfPrefix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> Index
|
||||
}
|
||||
|
||||
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"
|
||||
extension BidirectionalCollection {
|
||||
/// Returns the inclusive lower bound of the suffix of elements that satisfy
|
||||
/// the predicate.
|
||||
func startOfSuffix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> Index
|
||||
}
|
||||
```
|
||||
|
||||
### Complexity
|
||||
|
||||
+10
-2
@@ -1,4 +1,4 @@
|
||||
// swift-tools-version:5.4
|
||||
// swift-tools-version:6.0
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
@@ -12,6 +12,13 @@
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let availabilityDefinition = PackageDescription.SwiftSetting.unsafeFlags([
|
||||
"-Xfrontend",
|
||||
"-define-availability",
|
||||
"-Xfrontend",
|
||||
"SwiftStdlib 5.7:macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0",
|
||||
])
|
||||
|
||||
let package = Package(
|
||||
name: "swift-algorithms",
|
||||
products: [
|
||||
@@ -27,7 +34,8 @@ let package = Package(
|
||||
name: "Algorithms",
|
||||
dependencies: [
|
||||
.product(name: "RealModule", package: "swift-numerics"),
|
||||
]),
|
||||
],
|
||||
swiftSettings: [availabilityDefinition]),
|
||||
.testTarget(
|
||||
name: "SwiftAlgorithmsTests",
|
||||
dependencies: ["Algorithms"]),
|
||||
|
||||
@@ -2,55 +2,35 @@
|
||||
|
||||
**Swift Algorithms** is an open-source package of sequence and collection algorithms, along with their related types.
|
||||
|
||||
Read more about the package, and the intent behind it, in the [announcement on swift.org](https://swift.org/blog/swift-algorithms/).
|
||||
## Overview
|
||||
|
||||
## Contents
|
||||
The Algorithms package provides a variety of sequence and collection operations, letting you cycle over a collection's elements, find combinations and permutations, create a random sample, and more.
|
||||
|
||||
#### Combinations / permutations
|
||||
For example, the package includes a group of "chunking" methods, each of which breaks a collection into consecutive subsequences. One version tests adjacent elements to find the breaking point between chunks — you can use it to quickly separate an array into ascending runs:
|
||||
|
||||
- [`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.
|
||||
```swift
|
||||
let numbers = [10, 20, 30, 10, 40, 40, 10, 20]
|
||||
let chunks = numbers.chunked(by: { $0 <= $1 })
|
||||
// [[10, 20, 30], [10, 40, 40], [10, 20]]
|
||||
```
|
||||
|
||||
#### Mutating algorithms
|
||||
Another version looks for a change in the transformation of each successive value. You can use that to separate a list of names into groups by the first character:
|
||||
|
||||
- [`rotate(toStartAt:)`, `rotate(subrange:toStartAt:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Rotate.md): In-place rotation of elements.
|
||||
- [`stablePartition(by:)`, `stablePartition(subrange:by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Partition.md): A partition that preserves the relative order of the resulting prefix and suffix.
|
||||
```swift
|
||||
let names = ["Cassie", "Chloe", "Jasmine", "Jordan", "Taylor"]
|
||||
let chunks = names.chunked(on: \.first)
|
||||
// [["Cassie", "Chloe"], ["Jasmine", "Jordan"], ["Taylor"]]
|
||||
```
|
||||
|
||||
#### Combining collections
|
||||
Explore more chunking methods and the remainder of the `Algorithms` package in the links below.
|
||||
|
||||
- [`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.
|
||||
## Documentation
|
||||
|
||||
#### Subsetting operations
|
||||
For API documentation, see the library's official documentation in Xcode or on the Web.
|
||||
|
||||
- [`compacted()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Compacted.md): Drops the `nil`s from a sequence or collection, unwrapping the remaining elements.
|
||||
- [`partitioned(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Partition.md): Returns the elements in a sequence or collection that do and do not match a given predicate.
|
||||
- [`randomSample(count:)`, `randomSample(count:using:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/RandomSampling.md): Randomly selects a specific number of elements from a collection.
|
||||
- [`randomStableSample(count:)`, `randomStableSample(count:using:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/RandomSampling.md): Randomly selects a specific number of elements from a collection, preserving their original relative order.
|
||||
- [`striding(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Stride.md): Returns every nth element of a collection.
|
||||
- [`suffix(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Suffix.md): Returns the suffix of a collection where all element pass a given predicate.
|
||||
- [`trimmingPrefix(while:)`, `trimmingSuffix(while)`, `trimming(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Trim.md): Returns a slice by trimming elements from a collection's start, end, or both. The mutating `trim...` methods trim a collection in place.
|
||||
- [`uniqued()`, `uniqued(on:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Unique.md): The unique elements of a collection, preserving their order.
|
||||
- [`minAndMax()`, `minAndMax(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/MinMax.md): Returns the smallest and largest elements of a sequence.
|
||||
|
||||
#### Partial sorting
|
||||
|
||||
- [`min(count:)`, `max(count:)`, `min(count:sortedBy:)`, `max(count:sortedBy:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/MinMax.md): Returns the smallest or largest elements of a collection, sorted by a predicate.
|
||||
|
||||
#### 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/Split.md): Lazy versions of the Standard Library's eager operations that split sequences and collections into subsequences separated by the specified separator element.
|
||||
- [`windows(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Windows.md): Breaks a collection into overlapping subsequences where elements are slices from the original collection.
|
||||
- [API documentation][docs]
|
||||
- [Swift.org announcement][announcement]
|
||||
- [API Proposals/Guides][guides]
|
||||
|
||||
## Adding Swift Algorithms as a Dependency
|
||||
|
||||
@@ -58,7 +38,7 @@ To use the `Algorithms` library in a SwiftPM project,
|
||||
add the following line to the dependencies in your `Package.swift` file:
|
||||
|
||||
```swift
|
||||
.package(url: "https://github.com/apple/swift-algorithms", from: "1.0.0"),
|
||||
.package(url: "https://github.com/apple/swift-algorithms", from: "1.2.0"),
|
||||
```
|
||||
|
||||
Include `"Algorithms"` as a dependency for your executable target:
|
||||
@@ -75,8 +55,12 @@ Finally, add `import Algorithms` to your source code.
|
||||
|
||||
The Swift Algorithms package is source stable; version numbers follow [Semantic Versioning](https://semver.org/). Source breaking changes to public API can only land in a new major version.
|
||||
|
||||
The public API of version 1.0 of the `swift-algorithms` package consists of non-underscored declarations that are marked `public` in the `Algorithms` module. Interfaces that aren't part of the public API may continue to change in any release, including patch releases.
|
||||
The public API of the `swift-algorithms` package consists of non-underscored declarations that are marked `public` in the `Algorithms` module. Interfaces that aren't part of the public API may continue to change in any release, including patch releases.
|
||||
|
||||
Future minor versions of the package may introduce changes to these rules as needed.
|
||||
|
||||
We'd like this package to quickly embrace Swift language and toolchain improvements that are relevant to its mandate. Accordingly, from time to time, we expect that new versions of this package will require clients to upgrade to a more recent Swift toolchain release. Requiring a new Swift release will only require a minor version bump.
|
||||
|
||||
[docs]: https://swiftpackageindex.com/apple/swift-algorithms/documentation/algorithms
|
||||
[announcement]: https://swift.org/blog/swift-algorithms/
|
||||
[guides]: https://github.com/apple/swift-algorithms/tree/main/Guides
|
||||
@@ -456,9 +456,9 @@ extension Collection {
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
@inlinable
|
||||
public func chunked(
|
||||
by belongInSameGroup: (Element, Element) throws -> Bool
|
||||
) rethrows -> [SubSequence] {
|
||||
public func chunked<E: Error>(
|
||||
by belongInSameGroup: (Element, Element) throws(E) -> Bool
|
||||
) throws(E) -> [SubSequence] {
|
||||
guard !isEmpty else { return [] }
|
||||
var result: [SubSequence] = []
|
||||
|
||||
@@ -489,9 +489,9 @@ extension Collection {
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
@inlinable
|
||||
public func chunked<Subject: Equatable>(
|
||||
on projection: (Element) throws -> Subject
|
||||
) rethrows -> [(Subject, SubSequence)] {
|
||||
public func chunked<Subject: Equatable, E: Error>(
|
||||
on projection: (Element) throws(E) -> Subject
|
||||
) throws(E) -> [(Subject, SubSequence)] {
|
||||
guard !isEmpty else { return [] }
|
||||
var result: [(Subject, SubSequence)] = []
|
||||
|
||||
|
||||
@@ -78,6 +78,10 @@ public struct CombinationsSequence<Base: Collection> {
|
||||
binomial(n: n, k: $0)
|
||||
}.reduce(0, +)
|
||||
}
|
||||
|
||||
/// The total number of combinations.
|
||||
@inlinable
|
||||
public var underestimatedCount: Int { count }
|
||||
}
|
||||
|
||||
extension CombinationsSequence: Sequence {
|
||||
|
||||
@@ -33,6 +33,7 @@ Explore more chunking methods and the remainder of the Algorithms package, group
|
||||
- <doc:Joining>
|
||||
- <doc:Extending>
|
||||
- <doc:Trimming>
|
||||
- <doc:Keying>
|
||||
- <doc:Sampling>
|
||||
- <doc:MinAndMax>
|
||||
- <doc:Selecting>
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
# Keying and Grouping
|
||||
|
||||
Convert a sequence to a dictionary, providing keys to individual elements or to use as grouping values.
|
||||
|
||||
## Topics
|
||||
|
||||
### Creating a Keyed Dictionary
|
||||
|
||||
- ``Swift/Sequence/keyed(by:)``
|
||||
- ``Swift/Sequence/keyed(by:resolvingConflictsWith:)``
|
||||
|
||||
### Grouping Elements by Key
|
||||
|
||||
- ``Swift/Sequence/grouped(by:)``
|
||||
@@ -16,7 +16,7 @@ or a specific number of elements at the minimum and maximum.
|
||||
- ``Swift/Sequence/max(count:sortedBy:)``
|
||||
- ``Swift/Collection/max(count:sortedBy:)``
|
||||
|
||||
### Finding the Minimum and Maximum Elements Simulataneously
|
||||
### Finding the Minimum and Maximum Elements Simultaneously
|
||||
|
||||
- ``Swift/Sequence/minAndMax()``
|
||||
- ``Swift/Sequence/minAndMax(by:)``
|
||||
|
||||
@@ -25,3 +25,8 @@ Remove unwanted elements from the start, the end, or both ends of a collection.
|
||||
### Finding the Suffix of a Collection
|
||||
|
||||
- ``Swift/BidirectionalCollection/suffix(while:)``
|
||||
|
||||
### Finding Boundaries within a Collection
|
||||
|
||||
- ``Swift/Collection/endOfPrefix(while:)``
|
||||
- ``Swift/BidirectionalCollection/startOfSuffix(while:)``
|
||||
@@ -31,9 +31,9 @@ extension Sequence {
|
||||
/// - Complexity: O(*n*), where *n* is the number of elements at the start of
|
||||
/// the sequence that result in `nil` when applying the transformation.
|
||||
@inlinable
|
||||
public func firstNonNil<Result>(
|
||||
_ transform: (Element) throws -> Result?
|
||||
) rethrows -> Result? {
|
||||
public func firstNonNil<Result, E: Error>(
|
||||
_ transform: (Element) throws(E) -> Result?
|
||||
) throws(E) -> Result? {
|
||||
for value in self {
|
||||
if let value = try transform(value) {
|
||||
return value
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 {
|
||||
/// Groups up elements of `self` into a new Dictionary,
|
||||
/// whose values are Arrays of grouped elements,
|
||||
/// each keyed by the group key returned by the given closure.
|
||||
/// - Parameters:
|
||||
/// - keyForValue: A closure that returns a key for each element in
|
||||
/// `self`.
|
||||
/// - Returns: A dictionary containing grouped elements of self, keyed by
|
||||
/// the keys derived by the `keyForValue` closure.
|
||||
@inlinable
|
||||
public func grouped<GroupKey, E: Error>(
|
||||
by keyForValue: (Element) throws(E) -> GroupKey
|
||||
) throws(E) -> [GroupKey: [Element]] {
|
||||
do {
|
||||
// This stdlib Dictionary initializer doesn't use typed errors,
|
||||
// so we need to catch and cast any thrown error to our expected type.
|
||||
return try Dictionary(grouping: self, by: keyForValue)
|
||||
} catch {
|
||||
throw error as! E
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -355,9 +355,9 @@ extension Sequence where Element: Sequence {
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _joined(
|
||||
by update: (inout [Element.Element], Element, Element) throws -> Void
|
||||
) rethrows -> [Element.Element] {
|
||||
internal func _joined<E: Error>(
|
||||
by update: (inout [Element.Element], Element, Element) throws(E) -> Void
|
||||
) throws(E) -> [Element.Element] {
|
||||
var iterator = makeIterator()
|
||||
guard let first = iterator.next() else { return [] }
|
||||
|
||||
@@ -381,10 +381,14 @@ extension Sequence where Element: Sequence {
|
||||
/// }
|
||||
/// // 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)) })
|
||||
public func joined<E: Error>(
|
||||
by separator: (Element, Element) throws(E) -> Element.Element
|
||||
) throws(E) -> [Element.Element] {
|
||||
// An anonymous closure is inferred as `throws(any Error)`, so we give it
|
||||
// the correct type here.
|
||||
let joiner: (inout [Element.Element], Element, Element) throws(E) -> Void
|
||||
= { $0.append(try separator($1, $2)) }
|
||||
return try _joined(by: joiner)
|
||||
}
|
||||
|
||||
/// Returns the concatenation of the elements in this sequence of sequences,
|
||||
@@ -395,12 +399,16 @@ extension Sequence where Element: Sequence {
|
||||
/// }
|
||||
/// // 1, 2, 200, 300, 3, 4, 400, 500, 5, 6
|
||||
@inlinable
|
||||
public func joined<Separator>(
|
||||
by separator: (Element, Element) throws -> Separator
|
||||
) rethrows -> [Element.Element]
|
||||
public func joined<Separator, E: Error>(
|
||||
by separator: (Element, Element) throws(E) -> Separator
|
||||
) throws(E) -> [Element.Element]
|
||||
where Separator: Sequence, Separator.Element == Element.Element
|
||||
{
|
||||
try _joined(by: { $0.append(contentsOf: try separator($1, $2)) })
|
||||
// An anonymous closure is inferred as `throws(any Error)`, so we give it
|
||||
// the correct type here.
|
||||
let joiner: (inout [Element.Element], Element, Element) throws(E) -> Void
|
||||
= { $0.append(contentsOf: try separator($1, $2)) }
|
||||
return try _joined(by: joiner)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Executable
+68
@@ -0,0 +1,68 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Sequence {
|
||||
/// Creates a new Dictionary from the elements of `self`, keyed by the
|
||||
/// results returned by the given `keyForValue` closure.
|
||||
///
|
||||
/// If the key derived for a new element collides with an existing key from a previous element,
|
||||
/// the latest value will be kept.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - keyForValue: A closure that returns a key for each element in `self`.
|
||||
@inlinable
|
||||
public func keyed<Key, E: Error>(
|
||||
by keyForValue: (Element) throws(E) -> Key
|
||||
) throws(E) -> [Key: Element] {
|
||||
// An anonymous closure is inferred as `throws(any Error)`, so we give it
|
||||
// the correct type here.
|
||||
let resolve: (Key, Element, Element) throws(E) -> Element = { _, _, new in new }
|
||||
return try self.keyed(by: keyForValue, resolvingConflictsWith: resolve)
|
||||
}
|
||||
|
||||
/// Creates a new Dictionary from the elements of `self`, keyed by the
|
||||
/// results returned by the given `keyForValue` closure. As the dictionary is
|
||||
/// built, the initializer calls the `resolve` closure with the current and
|
||||
/// new values for any duplicate keys. Pass a closure as `resolve` that
|
||||
/// returns the value to use in the resulting dictionary: The closure can
|
||||
/// choose between the two values, combine them to produce a new value, or
|
||||
/// even throw an error.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - keyForValue: A closure that returns a key for each element in `self`.
|
||||
/// - resolve: A closure that is called with the values for any duplicate
|
||||
/// keys that are encountered. The closure returns the desired value for
|
||||
/// the final dictionary.
|
||||
@inlinable
|
||||
public func keyed<Key, E: Error>(
|
||||
by keyForValue: (Element) throws(E) -> Key,
|
||||
resolvingConflictsWith resolve: (Key, Element, Element) throws(E) -> Element
|
||||
) throws(E) -> [Key: Element] {
|
||||
var result = [Key: Element]()
|
||||
|
||||
for element in self {
|
||||
let key = try keyForValue(element)
|
||||
|
||||
if let oldValue = result.updateValue(element, forKey: key) {
|
||||
let valueToKeep = try resolve(key, oldValue, element)
|
||||
|
||||
// This causes a second look-up for the same key. The standard library can avoid that
|
||||
// by calling `mutatingFind` to get access to the bucket where the value will end up,
|
||||
// and updating in place.
|
||||
// Swift Algorithms doesn't have access to that API, so we make do.
|
||||
// When this gets merged into the standard library, we should optimize this.
|
||||
result[key] = valueToKeep
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -12,10 +12,10 @@
|
||||
extension Sequence {
|
||||
/// Implementation for min(count:areInIncreasingOrder:)
|
||||
@inlinable
|
||||
internal func _minImplementation(
|
||||
internal func _minImplementation<E: Error>(
|
||||
count: Int,
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows -> [Element] {
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws(E) -> Bool
|
||||
) throws(E) -> [Element] {
|
||||
var iterator = makeIterator()
|
||||
|
||||
var result: [Element] = []
|
||||
@@ -23,14 +23,22 @@ extension Sequence {
|
||||
while result.count < count, let e = iterator.next() {
|
||||
result.append(e)
|
||||
}
|
||||
try result.sort(by: areInIncreasingOrder)
|
||||
do {
|
||||
// The stdlib `sort(by:)` method doesn't use typed errors,
|
||||
// so we need to catch and cast any thrown error to our expected type.
|
||||
try result.sort(by: areInIncreasingOrder)
|
||||
} catch {
|
||||
throw error as! E
|
||||
}
|
||||
|
||||
while let e = iterator.next() {
|
||||
// To be part of `result`, `e` must be strictly less than `result.last`.
|
||||
guard try areInIncreasingOrder(e, result.last!) else { continue }
|
||||
result.removeLast()
|
||||
let insertionIndex =
|
||||
try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
|
||||
// An anonymous closure is inferred as `throws(any Error)`, so we give it
|
||||
// the correct type here.
|
||||
let pred: (Element) throws(E) -> Bool = { try areInIncreasingOrder(e, $0) }
|
||||
let insertionIndex = try result.partitioningIndex(where: pred)
|
||||
result.insert(e, at: insertionIndex)
|
||||
}
|
||||
|
||||
@@ -39,10 +47,10 @@ extension Sequence {
|
||||
|
||||
/// Implementation for max(count:areInIncreasingOrder:)
|
||||
@inlinable
|
||||
internal func _maxImplementation(
|
||||
internal func _maxImplementation<E: Error>(
|
||||
count: Int,
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows -> [Element] {
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws(E) -> Bool
|
||||
) throws(E) -> [Element] {
|
||||
var iterator = makeIterator()
|
||||
|
||||
var result: [Element] = []
|
||||
@@ -50,13 +58,21 @@ extension Sequence {
|
||||
while result.count < count, let e = iterator.next() {
|
||||
result.append(e)
|
||||
}
|
||||
try result.sort(by: areInIncreasingOrder)
|
||||
do {
|
||||
// The stdlib `sort(by:)` method doesn't use typed errors,
|
||||
// so we need to catch and cast any thrown error to our expected type.
|
||||
try result.sort(by: areInIncreasingOrder)
|
||||
} catch {
|
||||
throw error as! E
|
||||
}
|
||||
|
||||
while let e = iterator.next() {
|
||||
// To be part of `result`, `e` must be greater/equal to `result.first`.
|
||||
guard try !areInIncreasingOrder(e, result.first!) else { continue }
|
||||
let insertionIndex =
|
||||
try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
|
||||
// An anonymous closure is inferred as `throws(any Error)`, so we give it
|
||||
// the correct type here.
|
||||
let pred: (Element) throws(E) -> Bool = { try areInIncreasingOrder(e, $0) }
|
||||
let insertionIndex = try result.partitioningIndex(where: pred)
|
||||
|
||||
assert(insertionIndex > 0)
|
||||
// Inserting `e` and then removing the first element (or vice versa)
|
||||
@@ -101,10 +117,10 @@ extension Sequence {
|
||||
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
|
||||
/// sequence and *k* is `count`.
|
||||
@inlinable
|
||||
public func min(
|
||||
public func min<E: Error>(
|
||||
count: Int,
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows -> [Element] {
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws(E) -> Bool
|
||||
) throws(E) -> [Element] {
|
||||
precondition(count >= 0, """
|
||||
Cannot find a minimum with a negative count of elements!
|
||||
"""
|
||||
@@ -146,10 +162,10 @@ extension Sequence {
|
||||
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
|
||||
/// sequence and *k* is `count`.
|
||||
@inlinable
|
||||
public func max(
|
||||
public func max<E: Error>(
|
||||
count: Int,
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows -> [Element] {
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws(E) -> Bool
|
||||
) throws(E) -> [Element] {
|
||||
precondition(count >= 0, """
|
||||
Cannot find a maximum with a negative count of elements!
|
||||
"""
|
||||
@@ -247,27 +263,33 @@ extension Collection {
|
||||
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
|
||||
/// collection and *k* is `count`.
|
||||
@inlinable
|
||||
public func min(
|
||||
public func min<E: Error>(
|
||||
count: Int,
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows -> [Element] {
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws(E) -> Bool
|
||||
) throws(E) -> [Element] {
|
||||
precondition(count >= 0, """
|
||||
Cannot find a minimum with a negative count of elements!
|
||||
"""
|
||||
)
|
||||
|
||||
// Do nothing if we're prefixing nothing.
|
||||
guard count > 0 else {
|
||||
return []
|
||||
}
|
||||
|
||||
// Make sure we are within bounds.
|
||||
let prefixCount = Swift.min(count, self.count)
|
||||
|
||||
// Do nothing if we're prefixing nothing.
|
||||
guard prefixCount > 0 else {
|
||||
return []
|
||||
}
|
||||
|
||||
// If we're attempting to prefix more than 10% of the collection, it's
|
||||
// faster to sort everything.
|
||||
guard prefixCount < (self.count / 10) else {
|
||||
return Array(try sorted(by: areInIncreasingOrder).prefix(prefixCount))
|
||||
do {
|
||||
// The stdlib `sorted(by:)` method doesn't use typed errors,
|
||||
// so we need to catch and cast any thrown error to our expected type.
|
||||
return Array(try sorted(by: areInIncreasingOrder).prefix(prefixCount))
|
||||
} catch {
|
||||
throw error as! E
|
||||
}
|
||||
}
|
||||
|
||||
return try _minImplementation(count: count, sortedBy: areInIncreasingOrder)
|
||||
@@ -301,27 +323,33 @@ extension Collection {
|
||||
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
|
||||
/// collection and *k* is `count`.
|
||||
@inlinable
|
||||
public func max(
|
||||
public func max<E: Error>(
|
||||
count: Int,
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows -> [Element] {
|
||||
sortedBy areInIncreasingOrder: (Element, Element) throws(E) -> Bool
|
||||
) throws(E) -> [Element] {
|
||||
precondition(count >= 0, """
|
||||
Cannot find a maximum with a negative count of elements!
|
||||
"""
|
||||
)
|
||||
|
||||
// Do nothing if we're suffixing nothing.
|
||||
guard count > 0 else {
|
||||
return []
|
||||
}
|
||||
|
||||
// Make sure we are within bounds.
|
||||
let suffixCount = Swift.min(count, self.count)
|
||||
|
||||
// Do nothing if we're suffixing nothing.
|
||||
guard suffixCount > 0 else {
|
||||
return []
|
||||
}
|
||||
|
||||
// If we're attempting to prefix more than 10% of the collection, it's
|
||||
// faster to sort everything.
|
||||
guard suffixCount < (self.count / 10) else {
|
||||
return Array(try sorted(by: areInIncreasingOrder).suffix(suffixCount))
|
||||
do {
|
||||
// The stdlib `sorted(by:)` method doesn't use typed errors,
|
||||
// so we need to catch and cast any thrown error to our expected type.
|
||||
return Array(try sorted(by: areInIncreasingOrder).suffix(suffixCount))
|
||||
} catch {
|
||||
throw error as! E
|
||||
}
|
||||
}
|
||||
|
||||
return try _maxImplementation(count: count, sortedBy: areInIncreasingOrder)
|
||||
@@ -427,9 +455,9 @@ extension Sequence {
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
||||
@inlinable
|
||||
public func minAndMax(
|
||||
by areInIncreasingOrder: (Element, Element) throws -> Bool
|
||||
) rethrows -> (min: Element, max: Element)? {
|
||||
public func minAndMax<E: Error>(
|
||||
by areInIncreasingOrder: (Element, Element) throws(E) -> Bool
|
||||
) throws(E) -> (min: Element, max: Element)? {
|
||||
// Check short sequences.
|
||||
var iterator = makeIterator()
|
||||
guard var lowest = iterator.next() else { return nil }
|
||||
|
||||
@@ -22,11 +22,11 @@ extension MutableCollection {
|
||||
/// - Precondition:
|
||||
/// `n == distance(from: range.lowerBound, to: range.upperBound)`
|
||||
@inlinable
|
||||
internal mutating func stablePartition(
|
||||
internal mutating func stablePartition<E: Error>(
|
||||
count n: Int,
|
||||
subrange: Range<Index>,
|
||||
by belongsInSecondPartition: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
by belongsInSecondPartition: (Element) throws(E) -> Bool
|
||||
) throws(E) -> Index {
|
||||
if n == 0 { return subrange.lowerBound }
|
||||
if n == 1 {
|
||||
return try belongsInSecondPartition(self[subrange.lowerBound])
|
||||
@@ -58,10 +58,10 @@ extension MutableCollection {
|
||||
///
|
||||
/// - Complexity: O(*n* log *n*), where *n* is the length of this collection.
|
||||
@inlinable
|
||||
public mutating func stablePartition(
|
||||
public mutating func stablePartition<E: Error>(
|
||||
subrange: Range<Index>,
|
||||
by belongsInSecondPartition: (Element) throws-> Bool
|
||||
) rethrows -> Index {
|
||||
by belongsInSecondPartition: (Element) throws(E) -> Bool
|
||||
) throws(E) -> Index {
|
||||
try stablePartition(
|
||||
count: distance(from: subrange.lowerBound, to: subrange.upperBound),
|
||||
subrange: subrange,
|
||||
@@ -78,9 +78,9 @@ extension MutableCollection {
|
||||
///
|
||||
/// - Complexity: O(*n* log *n*), where *n* is the length of this collection.
|
||||
@inlinable
|
||||
public mutating func stablePartition(
|
||||
by belongsInSecondPartition: (Element) throws-> Bool
|
||||
) rethrows -> Index {
|
||||
public mutating func stablePartition<E: Error>(
|
||||
by belongsInSecondPartition: (Element) throws(E) -> Bool
|
||||
) throws(E) -> Index {
|
||||
try stablePartition(
|
||||
subrange: startIndex..<endIndex,
|
||||
by: belongsInSecondPartition)
|
||||
@@ -97,14 +97,22 @@ extension MutableCollection {
|
||||
///
|
||||
/// - Complexity: O(*n*) where n is the length of the collection.
|
||||
@inlinable
|
||||
public mutating func partition(
|
||||
public mutating func partition<E: Error>(
|
||||
subrange: Range<Index>,
|
||||
by belongsInSecondPartition: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
by belongsInSecondPartition: (Element) throws(E) -> Bool
|
||||
) throws(E) -> Index {
|
||||
// This version of `partition(subrange:)` is half stable; the elements in
|
||||
// the first partition retain their original relative order.
|
||||
guard var i = try self[subrange].firstIndex(where: belongsInSecondPartition)
|
||||
else { return subrange.upperBound }
|
||||
var i: Index
|
||||
do {
|
||||
// The stdlib `firstIndex(where:)` method doesn't use typed errors,
|
||||
// so we need to catch and cast any thrown error to our expected type.
|
||||
guard let firstI = try self[subrange].firstIndex(where: belongsInSecondPartition)
|
||||
else { return subrange.upperBound }
|
||||
i = firstI
|
||||
} catch {
|
||||
throw error as! E
|
||||
}
|
||||
|
||||
var j = index(after: i)
|
||||
while j != subrange.upperBound {
|
||||
@@ -125,10 +133,10 @@ extension MutableCollection where Self: BidirectionalCollection {
|
||||
///
|
||||
/// - Complexity: O(*n*) where n is the length of the collection.
|
||||
@inlinable
|
||||
public mutating func partition(
|
||||
public mutating func partition<E: Error>(
|
||||
subrange: Range<Index>,
|
||||
by belongsInSecondPartition: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
by belongsInSecondPartition: (Element) throws(E) -> Bool
|
||||
) throws(E) -> Index {
|
||||
var lo = subrange.lowerBound
|
||||
var hi = subrange.upperBound
|
||||
|
||||
@@ -185,9 +193,9 @@ extension Collection {
|
||||
/// - Complexity: O(log *n*), where *n* is the length of this collection if
|
||||
/// the collection conforms to `RandomAccessCollection`, otherwise O(*n*).
|
||||
@inlinable
|
||||
public func partitioningIndex(
|
||||
where belongsInSecondPartition: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
public func partitioningIndex<E: Error>(
|
||||
where belongsInSecondPartition: (Element) throws(E) -> Bool
|
||||
) throws(E) -> Index {
|
||||
var n = count
|
||||
var l = startIndex
|
||||
|
||||
@@ -210,8 +218,8 @@ extension Collection {
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Sequence {
|
||||
/// Returns two arrays containing, in order, the elements of the sequence that
|
||||
/// do and don’t satisfy the given predicate.
|
||||
/// Returns two arrays containing the elements of the sequence that
|
||||
/// don’t and do satisfy the given predicate, respectively.
|
||||
///
|
||||
/// In this example, `partitioned(by:)` is used to separate the input based on
|
||||
/// whether a name is shorter than five characters:
|
||||
@@ -230,13 +238,15 @@ extension Sequence {
|
||||
///
|
||||
/// - Returns: Two arrays with all of the elements of the receiver. The
|
||||
/// first array contains all the elements that `predicate` didn’t allow, and
|
||||
/// the second array contains all the elements that `predicate` allowed.
|
||||
/// the second array contains all the elements that `predicate` allowed. The
|
||||
/// order of the elements in the arrays matches the order of the elements in
|
||||
/// the original sequence.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
||||
@inlinable
|
||||
public func partitioned(
|
||||
by predicate: (Element) throws -> Bool
|
||||
) rethrows -> (falseElements: [Element], trueElements: [Element]) {
|
||||
public func partitioned<E: Error>(
|
||||
by predicate: (Element) throws(E) -> Bool
|
||||
) throws(E) -> (falseElements: [Element], trueElements: [Element]) {
|
||||
var lhs = [Element]()
|
||||
var rhs = [Element]()
|
||||
|
||||
@@ -253,8 +263,8 @@ extension Sequence {
|
||||
}
|
||||
|
||||
extension Collection {
|
||||
/// Returns two arrays containing, in order, the elements of the collection
|
||||
/// that do and don’t satisfy the given predicate.
|
||||
/// Returns two arrays containing the elements of the collection that
|
||||
/// don’t and do satisfy the given predicate, respectively.
|
||||
///
|
||||
/// In this example, `partitioned(by:)` is used to separate the input based on
|
||||
/// whether a name is shorter than five characters.
|
||||
@@ -273,13 +283,15 @@ extension Collection {
|
||||
///
|
||||
/// - Returns: Two arrays with all of the elements of the receiver. The
|
||||
/// first array contains all the elements that `predicate` didn’t allow, and
|
||||
/// the second array contains all the elements that `predicate` allowed.
|
||||
/// the second array contains all the elements that `predicate` allowed. The
|
||||
/// order of the elements in the arrays matches the order of the elements in
|
||||
/// the original collection.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
public func partitioned(
|
||||
by predicate: (Element) throws -> Bool
|
||||
) rethrows -> (falseElements: [Element], trueElements: [Element]) {
|
||||
public func partitioned<E: Error>(
|
||||
by predicate: (Element) throws(E) -> Bool
|
||||
) throws(E) -> (falseElements: [Element], trueElements: [Element]) {
|
||||
guard !self.isEmpty else {
|
||||
return ([], [])
|
||||
}
|
||||
@@ -296,40 +308,47 @@ extension Collection {
|
||||
// We will use this to partition the single array into two.
|
||||
var midPoint: Int = 0
|
||||
|
||||
let elements = try [Element](
|
||||
unsafeUninitializedCapacity: count,
|
||||
initializingWith: { buffer, initializedCount in
|
||||
var lhs = buffer.baseAddress!
|
||||
var rhs = lhs + buffer.count
|
||||
do {
|
||||
for element in self {
|
||||
if try predicate(element) {
|
||||
rhs -= 1
|
||||
rhs.initialize(to: element)
|
||||
} else {
|
||||
lhs.initialize(to: element)
|
||||
lhs += 1
|
||||
let elements: [Element]
|
||||
do {
|
||||
// This stdlib `Array` initializer doesn't use typed errors,
|
||||
// so we need to catch and cast any thrown error to our expected type.
|
||||
elements = try Array(
|
||||
unsafeUninitializedCapacity: count,
|
||||
initializingWith: { buffer, initializedCount in
|
||||
var lhs = buffer.baseAddress!
|
||||
var rhs = lhs + buffer.count
|
||||
do {
|
||||
for element in self {
|
||||
if try predicate(element) {
|
||||
rhs -= 1
|
||||
rhs.initialize(to: element)
|
||||
} else {
|
||||
lhs.initialize(to: element)
|
||||
lhs += 1
|
||||
}
|
||||
}
|
||||
|
||||
precondition(lhs == rhs, """
|
||||
Collection's `count` differed from the number of elements iterated.
|
||||
"""
|
||||
)
|
||||
|
||||
let rhsIndex = rhs - buffer.baseAddress!
|
||||
buffer[rhsIndex...].reverse()
|
||||
initializedCount = buffer.count
|
||||
|
||||
midPoint = rhsIndex
|
||||
} catch {
|
||||
let lhsCount = lhs - buffer.baseAddress!
|
||||
let rhsCount = (buffer.baseAddress! + buffer.count) - rhs
|
||||
buffer.baseAddress!.deinitialize(count: lhsCount)
|
||||
rhs.deinitialize(count: rhsCount)
|
||||
throw error
|
||||
}
|
||||
|
||||
precondition(lhs == rhs, """
|
||||
Collection's `count` differed from the number of elements iterated.
|
||||
"""
|
||||
)
|
||||
|
||||
let rhsIndex = rhs - buffer.baseAddress!
|
||||
buffer[rhsIndex...].reverse()
|
||||
initializedCount = buffer.count
|
||||
|
||||
midPoint = rhsIndex
|
||||
} catch {
|
||||
let lhsCount = lhs - buffer.baseAddress!
|
||||
let rhsCount = (buffer.baseAddress! + buffer.count) - rhs
|
||||
buffer.baseAddress!.deinitialize(count: lhsCount)
|
||||
rhs.deinitialize(count: rhsCount)
|
||||
throw error
|
||||
}
|
||||
})
|
||||
})
|
||||
} catch {
|
||||
throw error as! E
|
||||
}
|
||||
|
||||
let lhs = elements[..<midPoint]
|
||||
let rhs = elements[midPoint...]
|
||||
|
||||
@@ -10,8 +10,14 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// For log(_:) and root(_:_:)
|
||||
#if swift(>=5.11)
|
||||
internal import RealModule
|
||||
#elseif swift(>=5.10)
|
||||
import RealModule
|
||||
#else
|
||||
@_implementationOnly
|
||||
import RealModule
|
||||
#endif
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// randomStableSample(count:)
|
||||
|
||||
@@ -112,13 +112,16 @@ extension Sequence {
|
||||
///
|
||||
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
|
||||
@inlinable
|
||||
public func reductions<Result>(
|
||||
public func reductions<Result, E: Error>(
|
||||
_ initial: Result,
|
||||
_ transform: (Result, Element) throws -> Result
|
||||
) rethrows -> [Result] {
|
||||
try reductions(into: initial) { result, element in
|
||||
_ transform: (Result, Element) throws(E) -> Result
|
||||
) throws(E) -> [Result] {
|
||||
// An anonymous closure is inferred as `throws(any Error)`, so we give it
|
||||
// the correct type here.
|
||||
let reducer: (inout Result, Element) throws(E) -> Void = { result, element in
|
||||
result = try transform(result, element)
|
||||
}
|
||||
return try reductions(into: initial, reducer)
|
||||
}
|
||||
|
||||
/// Returns an array containing the accumulated results of combining the
|
||||
@@ -156,11 +159,10 @@ extension Sequence {
|
||||
///
|
||||
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
|
||||
@inlinable
|
||||
public func reductions<Result>(
|
||||
public func reductions<Result, E: Error>(
|
||||
into initial: Result,
|
||||
_ transform: (inout Result, Element) throws -> Void
|
||||
) rethrows -> [Result] {
|
||||
|
||||
_ transform: (inout Result, Element) throws(E) -> Void
|
||||
) throws(E) -> [Result] {
|
||||
var output = [Result]()
|
||||
output.reserveCapacity(underestimatedCount + 1)
|
||||
output.append(initial)
|
||||
@@ -415,9 +417,9 @@ extension Sequence {
|
||||
///
|
||||
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
|
||||
@inlinable
|
||||
public func reductions(
|
||||
_ transform: (Element, Element) throws -> Element
|
||||
) rethrows -> [Element] {
|
||||
public func reductions<E: Error>(
|
||||
_ transform: (Element, Element) throws(E) -> Element
|
||||
) throws(E) -> [Element] {
|
||||
var iterator = makeIterator()
|
||||
guard let initial = iterator.next() else { return [] }
|
||||
return try IteratorSequence(iterator).reductions(initial, transform)
|
||||
@@ -582,19 +584,19 @@ extension LazySequenceProtocol {
|
||||
extension Sequence {
|
||||
@available(*, deprecated, message: "Use reductions(_:_:) instead.")
|
||||
@inlinable
|
||||
public func scan<Result>(
|
||||
public func scan<Result, E: Error>(
|
||||
_ initial: Result,
|
||||
_ transform: (Result, Element) throws -> Result
|
||||
) rethrows -> [Result] {
|
||||
_ transform: (Result, Element) throws(E) -> Result
|
||||
) throws(E) -> [Result] {
|
||||
try reductions(initial, transform)
|
||||
}
|
||||
|
||||
@available(*, deprecated, message: "Use reductions(into:_:) instead.")
|
||||
@inlinable
|
||||
public func scan<Result>(
|
||||
public func scan<Result, E: Error>(
|
||||
into initial: Result,
|
||||
_ transform: (inout Result, Element) throws -> Void
|
||||
) rethrows -> [Result] {
|
||||
_ transform: (inout Result, Element) throws(E) -> Void
|
||||
) throws(E) -> [Result] {
|
||||
try reductions(into: initial, transform)
|
||||
}
|
||||
}
|
||||
@@ -612,9 +614,9 @@ extension LazySequenceProtocol {
|
||||
extension Sequence {
|
||||
@available(*, deprecated, message: "Use reductions(_:) instead.")
|
||||
@inlinable
|
||||
public func scan(
|
||||
_ transform: (Element, Element) throws -> Element
|
||||
) rethrows -> [Element] {
|
||||
public func scan<E: Error>(
|
||||
_ transform: (Element, Element) throws(E) -> Element
|
||||
) throws(E) -> [Element] {
|
||||
try reductions(transform)
|
||||
}
|
||||
}
|
||||
@@ -512,7 +512,7 @@ extension SplitCollection: Collection {
|
||||
var subsequenceStart = i.baseRange.upperBound
|
||||
if subsequenceStart < base.endIndex {
|
||||
// If we're not already at the end of the base collection, the previous
|
||||
// susequence ended with a separator. Start searching for the next
|
||||
// subsequence ended with a separator. Start searching for the next
|
||||
// subsequence at the following element.
|
||||
subsequenceStart = base.index(after: i.baseRange.upperBound)
|
||||
}
|
||||
|
||||
@@ -24,9 +24,9 @@ extension BidirectionalCollection {
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
public func suffix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> SubSequence {
|
||||
public func suffix<E: Error>(
|
||||
while predicate: (Element) throws(E) -> Bool
|
||||
) throws(E) -> SubSequence {
|
||||
try self[startOfSuffix(while: predicate)...]
|
||||
}
|
||||
}
|
||||
@@ -46,11 +46,11 @@ extension Collection {
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
internal func endOfPrefix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
public func endOfPrefix<E: Error>(
|
||||
while predicate: (Element) throws(E) -> Bool
|
||||
) throws(E) -> Index {
|
||||
var index = startIndex
|
||||
while try index != endIndex && predicate(self[index]) {
|
||||
while index != endIndex, try predicate(self[index]) {
|
||||
formIndex(after: &index)
|
||||
}
|
||||
return index
|
||||
@@ -72,9 +72,9 @@ extension BidirectionalCollection {
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@inlinable
|
||||
internal func startOfSuffix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
public func startOfSuffix<E: Error>(
|
||||
while predicate: (Element) throws(E) -> Bool
|
||||
) throws(E) -> Index {
|
||||
var index = endIndex
|
||||
while index != startIndex {
|
||||
let after = index
|
||||
|
||||
@@ -26,13 +26,12 @@ extension Collection {
|
||||
/// 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 {
|
||||
public func trimmingPrefix<E: Error>(
|
||||
while predicate: (Element) throws(E) -> Bool
|
||||
) throws(E) -> SubSequence {
|
||||
let start = try endOfPrefix(while: predicate)
|
||||
return self[start...]
|
||||
return self[start..<endIndex]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,14 +54,13 @@ extension Collection where Self: RangeReplaceableCollection {
|
||||
/// 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)
|
||||
public mutating func trimPrefix<E: Error>(
|
||||
while predicate: (Element) throws(E) -> Bool
|
||||
) throws(E) {
|
||||
let startOfResult = try endOfPrefix(while: predicate)
|
||||
removeSubrange(startIndex..<startOfResult)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,12 +79,12 @@ extension Collection where Self == Self.SubSequence {
|
||||
/// 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)
|
||||
public mutating func trimPrefix<E: Error>(
|
||||
while predicate: (Element) throws(E) -> Bool
|
||||
) throws(E) {
|
||||
let start = try endOfPrefix(while: predicate)
|
||||
self = self[start..<endIndex]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,12 +106,12 @@ extension BidirectionalCollection {
|
||||
/// omitted from the resulting slice.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of this collection.
|
||||
///
|
||||
@inlinable
|
||||
public func trimming(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> SubSequence {
|
||||
try trimmingPrefix(while: predicate).trimmingSuffix(while: predicate)
|
||||
public func trimming<E: Error>(
|
||||
while predicate: (Element) throws(E) -> Bool
|
||||
) throws(E) -> SubSequence {
|
||||
let start = try endOfPrefix(while: predicate)
|
||||
return try self[start..<endIndex].trimmingSuffix(while: predicate)
|
||||
}
|
||||
|
||||
/// Returns a `SubSequence` formed by discarding all elements at the end of
|
||||
@@ -129,13 +127,12 @@ extension BidirectionalCollection {
|
||||
/// 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 {
|
||||
public func trimmingSuffix<E: Error>(
|
||||
while predicate: (Element) throws(E) -> Bool
|
||||
) throws(E) -> SubSequence {
|
||||
let end = try startOfSuffix(while: predicate)
|
||||
return self[..<end]
|
||||
return self[startIndex..<end]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,14 +155,14 @@ extension BidirectionalCollection where Self: RangeReplaceableCollection {
|
||||
/// 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 {
|
||||
public mutating func trim<E: Error>(
|
||||
while predicate: (Element) throws(E) -> Bool
|
||||
) throws(E) {
|
||||
let start = try endOfPrefix(while: predicate)
|
||||
self.removeSubrange(startIndex..<start)
|
||||
try trimSuffix(while: predicate)
|
||||
try trimPrefix(while: predicate)
|
||||
}
|
||||
|
||||
/// Mutates a `BidirectionalCollection` by discarding all elements at the end
|
||||
@@ -182,14 +179,13 @@ extension BidirectionalCollection where Self: RangeReplaceableCollection {
|
||||
/// 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)
|
||||
public mutating func trimSuffix<E: Error>(
|
||||
while predicate: (Element) throws(E) -> Bool
|
||||
) throws(E) {
|
||||
let endOfResult = try startOfSuffix(while: predicate)
|
||||
removeSubrange(endOfResult..<endIndex)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,11 +204,10 @@ extension BidirectionalCollection where Self == Self.SubSequence {
|
||||
/// 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 {
|
||||
public mutating func trim<E: Error>(
|
||||
while predicate: (Element) throws(E) -> Bool
|
||||
) throws(E) {
|
||||
self = try trimming(while: predicate)
|
||||
}
|
||||
|
||||
@@ -230,11 +225,10 @@ extension BidirectionalCollection where Self == Self.SubSequence {
|
||||
/// 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 {
|
||||
public mutating func trimSuffix<E: Error>(
|
||||
while predicate: (Element) throws(E) -> Bool
|
||||
) throws(E) {
|
||||
self = try trimmingSuffix(while: predicate)
|
||||
}
|
||||
}
|
||||
@@ -112,9 +112,9 @@ extension Sequence {
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
||||
@inlinable
|
||||
public func uniqued<Subject: Hashable>(
|
||||
on projection: (Element) throws -> Subject
|
||||
) rethrows -> [Element] {
|
||||
public func uniqued<Subject: Hashable, E: Error>(
|
||||
on projection: (Element) throws(E) -> Subject
|
||||
) throws(E) -> [Element] {
|
||||
var seen: Set<Subject> = []
|
||||
var result: [Element] = []
|
||||
for element in self {
|
||||
|
||||
@@ -15,57 +15,63 @@ import Algorithms
|
||||
final class CombinationsTests: XCTestCase {
|
||||
func testCount() {
|
||||
let c = "ABCD"
|
||||
|
||||
let c0 = c.combinations(ofCount: 0).count
|
||||
XCTAssertEqual(c0, 1)
|
||||
|
||||
let c1 = c.combinations(ofCount: 1).count
|
||||
XCTAssertEqual(c1, 4)
|
||||
|
||||
let c2 = c.combinations(ofCount: 2).count
|
||||
XCTAssertEqual(c2, 6)
|
||||
|
||||
let c3 = c.combinations(ofCount: 3).count
|
||||
XCTAssertEqual(c3, 4)
|
||||
|
||||
let c4 = c.combinations(ofCount: 4).count
|
||||
XCTAssertEqual(c4, 1)
|
||||
|
||||
let c5 = c.combinations(ofCount: 0...0).count
|
||||
XCTAssertEqual(c5, 1)
|
||||
|
||||
let c6 = c.combinations(ofCount: 1...1).count
|
||||
XCTAssertEqual(c6, 4)
|
||||
|
||||
let c7 = c.combinations(ofCount: 1...2).count
|
||||
XCTAssertEqual(c7, 10)
|
||||
|
||||
let c8 = c.combinations(ofCount: 1...3).count
|
||||
XCTAssertEqual(c8, 14)
|
||||
|
||||
let c9 = c.combinations(ofCount: 2...4).count
|
||||
XCTAssertEqual(c9, 11)
|
||||
|
||||
/// XCTAsserts that `x`'s `count` and `underestimatedCount` are both `l` at
|
||||
/// the given `file` and `line`.
|
||||
func check(
|
||||
_ x: CombinationsSequence<String>, countsAre l: Int,
|
||||
file: StaticString, line: UInt)
|
||||
{
|
||||
XCTAssertEqual(x.count, l, "unexpected count", file: file, line: line)
|
||||
XCTAssertEqual(
|
||||
x.underestimatedCount, l, "unexpected underestimatedCount",
|
||||
file: file, line: line)
|
||||
}
|
||||
|
||||
/// XCTAsserts that the `count` and `underestimatedCount` of
|
||||
/// `c.combinations(ofCount: l)` are both `n` at the given `file` and
|
||||
/// `line`.
|
||||
func check(
|
||||
cHas n: Int,
|
||||
combinationsOfLength l: Int,
|
||||
file: StaticString = #filePath, line: UInt = #line)
|
||||
{
|
||||
check(c.combinations(ofCount: l), countsAre: n, file: file, line: line)
|
||||
}
|
||||
|
||||
/// XCTAsserts that the `count` and `underestimatedCount` of
|
||||
/// `c.combinations(ofCount: l)` are both `n` at the given `file` and
|
||||
/// `line`.
|
||||
func check<R: RangeExpression>(
|
||||
cHas n: Int,
|
||||
combinationsOfLengths l: R,
|
||||
file: StaticString = #filePath, line: UInt = #line) where R.Bound == Int
|
||||
{
|
||||
check(c.combinations(ofCount: l), countsAre: n, file: file, line: line)
|
||||
}
|
||||
|
||||
check(cHas: 1, combinationsOfLength: 0)
|
||||
check(cHas: 4, combinationsOfLength: 1)
|
||||
check(cHas: 6, combinationsOfLength: 2)
|
||||
check(cHas: 1, combinationsOfLength: 4)
|
||||
|
||||
check(cHas: 1, combinationsOfLengths: 0...0)
|
||||
check(cHas: 4, combinationsOfLengths: 1...1)
|
||||
check(cHas: 10, combinationsOfLengths: 1...2)
|
||||
check(cHas: 14, combinationsOfLengths: 1...3)
|
||||
check(cHas: 11, combinationsOfLengths: 2...4)
|
||||
|
||||
// `k` greater than element count results in same number of combinations
|
||||
check(cHas: 5, combinationsOfLengths: 3...10)
|
||||
|
||||
// `k` greater than element count results in same number of combinations
|
||||
let c10 = c.combinations(ofCount: 3...10).count
|
||||
XCTAssertEqual(c10, 5)
|
||||
|
||||
// `k` greater than element count results in same number of combinations
|
||||
let c11 = c.combinations(ofCount: 4...10).count
|
||||
XCTAssertEqual(c11, 1)
|
||||
check(cHas: 1, combinationsOfLengths: 4...10)
|
||||
|
||||
// `k` entirely greater than element count results in no combinations
|
||||
let c12 = c.combinations(ofCount: 5...10).count
|
||||
XCTAssertEqual(c12, 0)
|
||||
check(cHas: 0, combinationsOfLengths: 5...10)
|
||||
|
||||
let c13 = c.combinations(ofCount: 0...).count
|
||||
XCTAssertEqual(c13, 16)
|
||||
|
||||
let c14 = c.combinations(ofCount: ...3).count
|
||||
XCTAssertEqual(c14, 15)
|
||||
|
||||
let c15 = c.combinations(ofCount: 0...).count
|
||||
XCTAssertEqual(c15, 16)
|
||||
check(cHas: 16, combinationsOfLengths: 0...)
|
||||
check(cHas: 15, combinationsOfLengths: ...3)
|
||||
}
|
||||
|
||||
func testCombinations() {
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 GroupedTests: XCTestCase {
|
||||
private final class SampleError: Error {}
|
||||
|
||||
// Based on https://github.com/apple/swift/blob/4d1d8a9de5ebc132a17aee9fc267461facf89bf8/validation-test/stdlib/Dictionary.swift#L1974-L1988
|
||||
|
||||
func testGroupedBy() {
|
||||
let r = 0..<10
|
||||
|
||||
let d1 = r.grouped(by: { $0 % 3 })
|
||||
XCTAssertEqual(3, d1.count)
|
||||
XCTAssertEqual(d1[0]!, [0, 3, 6, 9])
|
||||
XCTAssertEqual(d1[1]!, [1, 4, 7])
|
||||
XCTAssertEqual(d1[2]!, [2, 5, 8])
|
||||
|
||||
let d2 = r.grouped(by: { $0 })
|
||||
XCTAssertEqual(10, d2.count)
|
||||
|
||||
let d3 = (0..<0).grouped(by: { $0 })
|
||||
XCTAssertEqual(0, d3.count)
|
||||
}
|
||||
|
||||
func testThrowingFromKeyFunction() {
|
||||
let input = ["Apple", "Banana", "Cherry"]
|
||||
let error = SampleError()
|
||||
|
||||
XCTAssertThrowsError(
|
||||
try input.grouped(by: { (_: String) -> Character in throw error })
|
||||
) { thrownError in
|
||||
XCTAssertIdentical(error, thrownError as? SampleError)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 KeyedTests: XCTestCase {
|
||||
private final class SampleError: Error {}
|
||||
|
||||
func testUniqueKeys() {
|
||||
let d = ["Apple", "Banana", "Cherry"].keyed(by: { $0.first! })
|
||||
XCTAssertEqual(d.count, 3)
|
||||
XCTAssertEqual(d["A"]!, "Apple")
|
||||
XCTAssertEqual(d["B"]!, "Banana")
|
||||
XCTAssertEqual(d["C"]!, "Cherry")
|
||||
XCTAssertNil(d["D"])
|
||||
}
|
||||
|
||||
func testEmpty() {
|
||||
let d = EmptyCollection<String>().keyed(by: { $0.first! })
|
||||
XCTAssertEqual(d.count, 0)
|
||||
}
|
||||
|
||||
func testNonUniqueKeys() throws {
|
||||
let d = ["Apple", "Avocado", "Banana", "Cherry"].keyed(by: { $0.first! })
|
||||
XCTAssertEqual(d.count, 3)
|
||||
XCTAssertEqual(d["A"]!, "Avocado", "On a key-collision, keyed(by:) should take the latest value.")
|
||||
XCTAssertEqual(d["B"]!, "Banana")
|
||||
XCTAssertEqual(d["C"]!, "Cherry")
|
||||
}
|
||||
|
||||
func testNonUniqueKeysWithMergeFunction() {
|
||||
var resolveCallHistory = [(key: Character, current: String, new: String)]()
|
||||
let expectedCallHistory = [
|
||||
(key: "A", current: "Apple", new: "Avocado"),
|
||||
(key: "C", current: "Cherry", new: "Coconut"),
|
||||
]
|
||||
|
||||
let d = ["Apple", "Avocado", "Banana", "Cherry", "Coconut"].keyed(
|
||||
by: { $0.first! },
|
||||
resolvingConflictsWith: { key, older, newer in
|
||||
resolveCallHistory.append((key, older, newer))
|
||||
return "\(older)-\(newer)"
|
||||
}
|
||||
)
|
||||
|
||||
XCTAssertEqual(d.count, 3)
|
||||
XCTAssertEqual(d["A"]!, "Apple-Avocado")
|
||||
XCTAssertEqual(d["B"]!, "Banana")
|
||||
XCTAssertEqual(d["C"]!, "Cherry-Coconut")
|
||||
XCTAssertNil(d["D"])
|
||||
|
||||
XCTAssertEqual(
|
||||
resolveCallHistory.map(String.init(describing:)), // quick/dirty workaround: tuples aren't Equatable
|
||||
expectedCallHistory.map(String.init(describing:))
|
||||
)
|
||||
}
|
||||
|
||||
func testThrowingFromKeyFunction() {
|
||||
let input = ["Apple", "Banana", "Cherry"]
|
||||
let error = SampleError()
|
||||
|
||||
XCTAssertThrowsError(
|
||||
try input.keyed(by: { (_: String) -> Character in throw error })
|
||||
) { thrownError in
|
||||
XCTAssertIdentical(error, thrownError as? SampleError)
|
||||
}
|
||||
}
|
||||
|
||||
func testThrowingFromCombineFunction() {
|
||||
let input = ["Apple", "Avocado", "Banana", "Cherry"]
|
||||
let error = SampleError()
|
||||
|
||||
XCTAssertThrowsError(
|
||||
try input.keyed(by: { $0.first! }, resolvingConflictsWith: { _, _, _ in throw error })
|
||||
) { thrownError in
|
||||
XCTAssertIdentical(error, thrownError as? SampleError)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
@testable import Algorithms
|
||||
import Algorithms
|
||||
|
||||
final class SuffixTests: XCTestCase {
|
||||
func testSuffix() {
|
||||
|
||||
@@ -216,7 +216,7 @@ extension IndexValidator {
|
||||
/// - expectedCount:
|
||||
///
|
||||
/// - Complexity: O(*n*^3) where *n* is the length of the collection if the
|
||||
/// collection conforms to `RandomAccesCollection`, otherwise O(*n*^4).
|
||||
/// collection conforms to `RandomAccessCollection`, otherwise O(*n*^4).
|
||||
func validate(
|
||||
_ collection: C,
|
||||
expectedCount: Int? = nil,
|
||||
|
||||
@@ -75,9 +75,10 @@ final class TrimTests: XCTestCase {
|
||||
}
|
||||
|
||||
// Self == Self.Subsequence
|
||||
func testTrimPrefixNoAmbiguity() {
|
||||
func testTrimPrefixNoAmbiguity() throws {
|
||||
var values = [2, 10, 12, 15, 20, 100] as ArraySlice
|
||||
values.trimPrefix { $0.isMultiple(of: 2) }
|
||||
// FIXME: `trimPrefix` in the _StringProcessing module always `throws`
|
||||
try values.trimPrefix { $0.isMultiple(of: 2) }
|
||||
XCTAssertEqual(values, [15, 20, 100])
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user