diff --git a/.github/ISSUE_TEMPLATE/BUG_REPORT.md b/.github/ISSUE_TEMPLATE/BUG_REPORT.md index 6c47f5b..9e89558 100755 --- a/.github/ISSUE_TEMPLATE/BUG_REPORT.md +++ b/.github/ISSUE_TEMPLATE/BUG_REPORT.md @@ -16,7 +16,7 @@ about: Something isn't working as expected Replace this paragraph with a short description of the incorrect incorrect behavior. If this is a regression, please note the last version that the behavior was correct in addition to your current version. -**Swift Algorithms version:** `0.0.1` or the `main` branch, for example. +**Swift Algorithms version:** `1.0.0` or the `main` branch, for example. **Swift version:** Paste the output of `swift --version` here. ### Checklist diff --git a/CHANGELOG.md b/CHANGELOG.md index f57e0a7..b070cf5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,11 +4,7 @@ Add new items at the end of the relevant section under **Unreleased**. --> -This project follows semantic versioning. While still in major version `0`, -source-stability is only guaranteed within minor versions (e.g. between -`0.0.3` and `0.0.4`). If you want to guard against potentially source-breaking -package updates, you can specify your package dependency using -`.upToNextMinor(from: "0.1.0")` as the requirement. +This project follows semantic versioning. ## [Unreleased] @@ -16,6 +12,73 @@ package updates, you can specify your package dependency using --- +## [1.0.0] - 2021-09-08 + +### Changes + +- Most sequence and collection types have been renamed, following a more + consistent naming structure: + - The `Lazy` prefix was dropped. + - Either a `Sequence` or `Collection` suffix was added depending on whether or + not the type is unconditionally a collection. + - The base name was derived from the name of the method that produces it, + including an argument label to disambiguate if necessary. + ``` + Chain2 -> Chain2Sequence + ChunkedBy -> ChunkedByCollection + ChunkedOn -> ChunkedOnCollection + ChunkedByCount -> ChunksOfCountCollection + Combinations -> CombinationsSequence + Cycle -> CycledSequence + FiniteCycle -> CycledTimesCollection + Indexed -> IndexedCollection + Intersperse -> InterspersedSequence + LazySplitSequence -> SplitSequence + LazySplitCollection -> SplitCollection + Permutations -> PermutationsSequence + UniquePermutations -> UniquePermutationsSequence + Product2 -> Product2Sequence + ExclusiveReductions -> ExclusiveReductionsSequence + InclusiveReductions -> InclusiveReductionsSequence + StrideSequence -> StridingSequence + StrideCollection -> StridingCollection + Uniqued -> UniquedSequence + Windows -> WindowsOfCountCollection + ``` +- Types that can only be produced from a lazy sequence chain now unconditionally + conform to `LazySequenceProtocol` and wrap the base sequence instead of the + lazy wrapper, making some return types slightly simpler. + - e.g. `[1, 2, 3].lazy.reductions(+)` now returns + `ExclusiveReductionsSequence<[Int]>`, not + `ExclusiveReductionsSequence>`. + - This concerns `JoinedByClosureSequence`, `JoinedByClosureCollection`, + `ExclusiveReductionsSequence`, `InclusiveReductionsSequence`. +- The generic parameters of the `ExclusiveReductions` type have been swapped, + putting the base collection first and the result type second. +- The `Indices` associated type of `IndexedCollection` now matches + `Base.Indices`. + +### Removals + +- Previously deprecated type and method names have been removed: + - The `Chain` type alias for `Chain2Sequence` + - The `chained(with:)` method which was replaced with the `chain(_:_:)` free + function + - The `LazyChunked` and `Chunked` type aliases for `ChunkedByCollection` + - The `rotate(subrange:at:)` and `rotate(at:)` methods which were renamed to + `rotate(subrange:toStartAt:)` and `rotate(toStartAt:)` respectively + +### Fixes + +- The `StridingSequence` and `StridingCollection` types now conditionally + conform to `LazySequenceProtocol`, allowing the `striding(by:)` method to + properly propagate laziness in a lazy sequence chain. +- Fixed `chunked(by:)` to always compare two consecutive elements rather than + each element with the first element of the current chunk. ([#162]) + +The 1.0.0 release includes contributions from [iainsmith], [mdznr], and +[timvermeulen]. Thank you! + ## [0.2.1] - 2021-06-01 ### Additions @@ -206,7 +269,8 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co -[Unreleased]: https://github.com/apple/swift-algorithms/compare/0.2.1...HEAD +[Unreleased]: https://github.com/apple/swift-algorithms/compare/1.0.0...HEAD +[1.0.0]: https://github.com/apple/swift-algorithms/compare/0.2.1...1.0.0 [0.2.1]: https://github.com/apple/swift-algorithms/compare/0.2.0...0.2.1 [0.2.0]: https://github.com/apple/swift-algorithms/compare/0.1.1...0.2.0 [0.1.1]: https://github.com/apple/swift-algorithms/compare/0.1.0...0.1.1 @@ -243,6 +307,7 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co [#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 +[#162]: https://github.com/apple/swift-algorithms/pull/162 @@ -256,6 +321,7 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co [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 +[iainsmith]: https://github.com/apple/swift-algorithms/commits?author=iainsmith [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 diff --git a/Guides/AdjacentPairs.md b/Guides/AdjacentPairs.md index 1b790eb..32a6652 100644 --- a/Guides/AdjacentPairs.md +++ b/Guides/AdjacentPairs.md @@ -5,7 +5,8 @@ Lazily iterates over tuples of adjacent elements. -This operation is available for any sequence by calling the `adjacentPairs()` method. +This operation is available for any sequence by calling the `adjacentPairs()` +method. ```swift let numbers = (1...5) @@ -15,21 +16,26 @@ let pairs = numbers.adjacentPairs() ## Detailed Design -The `adjacentPairs()` method is declared as a `Sequence` extension returning `AdjacentPairsSequence` and as a `Collection` extension returning `AdjacentPairsCollection`. +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 + public func adjacentPairs() -> AdjacentPairsSequence } ``` ```swift extension Collection { - public func adjacentPairs() -> AdjacentPairsCollection + public func adjacentPairs() -> AdjacentPairsCollection } ``` -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. +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 @@ -37,16 +43,21 @@ 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/ +This method is named for clarity while remaining agnostic to any particular +domain of programming. In natural language processing, this operation is akin to +computing a list of bigrams; however, this algorithm is not specific to this use +case. ### Comparison with other languages -This function is often written as a `zip` of a sequence together with itself, minus its first element. +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. +**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`. + Note that in Swift, the spelling `zip(s, s.dropFirst())` is undefined behavior + for a single-pass sequence `s`. diff --git a/Guides/Chain.md b/Guides/Chain.md index f909c44..ce5671c 100644 --- a/Guides/Chain.md +++ b/Guides/Chain.md @@ -25,13 +25,13 @@ the shared conformances of the two underlying types. The `chain(_:_:)` function takes two sequences as arguments: ```swift -public func chain(_ s1: S1, _ s2: S2) -> Chain2 +public func chain(_ s1: S1, _ s2: S2) -> Chain2Sequence where S1.Element == S2.Element ``` -The resulting `Chain2` type is a sequence, with conditional conformance to -`Collection`, `BidirectionalCollection`, and `RandomAccessCollection` when both -the first and second arguments conform. +The resulting `Chain2Sequence` type is a sequence, with conditional conformance +to `Collection`, `BidirectionalCollection`, and `RandomAccessCollection` when +both the first and second arguments conform. ### Naming diff --git a/Guides/Chunked.md b/Guides/Chunked.md index b8d7fca..4b230c0 100644 --- a/Guides/Chunked.md +++ b/Guides/Chunked.md @@ -4,9 +4,9 @@ [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/ChunkedTests.swift)] Break a collection into subsequences where consecutive elements pass a binary -predicate, or where all elements in each chunk project to the same value. +predicate, or where all elements in each chunk project to the same value. -Also, includes a `chunks(ofCount:)` that breaks a collection into subsequences +Also includes a `chunks(ofCount:)` that breaks a collection into subsequences of a given `count`. There are two variations of the `chunked` method: `chunked(by:)` and @@ -20,10 +20,10 @@ let chunks = numbers.chunked(by: { $0 <= $1 }) // [[10, 20, 30], [10, 40, 40], [10, 20]] ``` -The `chunk(on:)` method, by contrast, takes a projection of each element and +The `chunked(on:)` method, by contrast, takes a projection of each element and separates chunks where the projection of two consecutive elements is not equal. -The result includes both the projected value and the subsequence -that groups elements with that projected value: +The result includes both the projected value and the subsequence that groups +elements with that projected value: ```swift let names = ["David", "Kyle", "Karoy", "Nate"] @@ -31,11 +31,11 @@ let chunks = names.chunked(on: \.first!) // [("D", ["David"]), ("K", ["Kyle", "Karoy"]), ("N", ["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:)` 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. ```swift let names = ["David", "Kyle", "Karoy", "Nate"] @@ -46,11 +46,11 @@ let remaining = names.chunks(ofCount: 3) // equivalent to [["David", "Kyle", "Karoy"], ["Nate"]] ``` -The `chunks(ofCount:)` is the subject of an [existing SE proposal][proposal]. +The `chunks(ofCount:)` is the subject of an [existing SE proposal][proposal]. -When "chunking" a collection, the entire collection is included in the result, +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. +Joining the result of a chunking method call recreates the original collection. ```swift c.elementsEqual(c.chunked(...).joined()) @@ -61,33 +61,38 @@ c.elementsEqual(c.chunked(...).joined()) ## Detailed Design -The two methods are added as extension to `Collection`, with two matching -versions that return a lazy wrapper added to `LazyCollectionProtocol`. +The three methods are added as extension to `Collection`. `chunked(by:)` and +`chunked(on:)` are eager by default, both with a matching version that return a +lazy wrapper added to `LazySequenceProtocol`. ```swift extension Collection { - public func chunked( - by belongInSameGroup: (Element, Element) -> Bool - ) -> [SubSequence] + public func chunked( + by belongInSameGroup: (Element, Element) -> Bool + ) -> [SubSequence] - public func chunked( - on projection: (Element) -> Subject - ) -> [(Subject, SubSequence)] - } + public func chunked( + on projection: (Element) -> Subject + ) -> [(Subject, SubSequence)] + + public func chunks(ofCount count: Int) -> ChunksOfCountCollection +} - extension LazyCollectionProtocol { - public func chunked( - by belongInSameGroup: @escaping (Element, Element) -> Bool - ) -> ChunkedBy +extension LazySequenceProtocol where Self: Collection, Elements: Collection { + public func chunked( + by belongInSameGroup: @escaping (Element, Element) -> Bool + ) -> ChunkedByCollection - public func chunked( - on projection: @escaping (Element) -> Subject - ) -> ChunkedOn + public func chunked( + on projection: @escaping (Element) -> Subject + ) -> ChunkedOnCollection } ``` -The `ChunkedBy` and `ChunkedOn` types are bidirectional when the wrapped collection is -bidirectional. +The `ChunkedByCollection`, `ChunkedOnCollection`, and `ChunksOfCountCollection` +types are bidirectional when the wrapped collection is bidirectional. +`ChunksOfCountCollection` also conforms to `LazySequenceProtocol` when the base +collection conforms. ### Complexity @@ -95,12 +100,20 @@ The eager methods are O(_n_), the lazy methods are O(_1_). ### Naming -The operation performed by these methods is similar to other ways of breaking a collection up into subsequences. In particular, the predicate-based `split(where:)` method looks similar to `chunked(on:)`. You can draw a distinction between these different operations based on the resulting subsequences: - -- `split`: *In the standard library.* Breaks a collection into subsequences, removing any elements that are considered "separators". The original collection cannot be recovered from the result of splitting. -- `chunked`: *In this package.* Breaks a collection into subsequences, preserving each element in its initial ordering. Joining the resulting subsequences re-forms the original collection. -- `sliced`: *Not included in this package or the stdlib.* Breaks a collection into potentially overlapping subsequences. +The operation performed by these methods is similar to other ways of breaking a +collection up into subsequences. In particular, the predicate-based +`split(where:)` method looks similar to `chunked(on:)`. You can draw a +distinction between these different operations based on the resulting +subsequences: +- `split`: *In the standard library.* Breaks a collection into subsequences, +removing any elements that are considered "separators". The original collection +cannot be recovered from the result of splitting. +- `chunked`: *In this package.* Breaks a collection into subsequences, +preserving each element in its initial ordering. Joining the resulting +subsequences re-forms the original collection. +- `sliced`: *Not included in this package or the stdlib.* Breaks a collection +into potentially overlapping subsequences. ### Comparison with other languages diff --git a/Guides/Combinations.md b/Guides/Combinations.md index b52400f..2428ae9 100644 --- a/Guides/Combinations.md +++ b/Guides/Combinations.md @@ -60,27 +60,28 @@ for combo in numbers.combinations(ofCount: 2...3) { ## Detailed Design The `combinations(ofCount:)` method is declared as a `Collection` extension, -and returns a `Combinations` type: +and returns a `CombinationsSequence` type: ```swift extension Collection { - public func combinations(ofCount k: Int) -> Combinations + public func combinations(ofCount k: Int) -> CombinationsSequence } ``` -Since the `Combinations` type needs to store an array of the collection’s -indices and mutate the array to generate each permutation, `Combinations` only -has `Sequence` conformance. Adding `Collection` conformance would require -storing the array in the index type, which would in turn lead to copying the -array at every index advancement. `Combinations` does conform to -`LazySequenceProtocol` when the base type conforms. +Since the `CombinationsSequence` type needs to store an array of the +collection’s indices and mutate the array to generate each permutation, +`CombinationsSequence` only has `Sequence` conformance. Adding `Collection` +conformance would require storing the array in the index type, which would in +turn lead to copying the array at every index advancement. +`CombinationsSequence` does conform to `LazySequenceProtocol` when the base type +conforms. ### Complexity Calling `combinations(ofCount:)` accesses the count of the collection, so it’s an O(1) operation for random-access collections, or an O(_n_) operation -otherwise. Creating the iterator for a `Combinations` instance and each call to -`Combinations.Iterator.next()` is an O(_n_) operation. +otherwise. Creating the iterator for a `CombinationsSequence` instance and each +call to `CombinationsSequence.Iterator.next()` is an O(_n_) operation. ### Naming diff --git a/Guides/Compacted.md b/Guides/Compacted.md index 9e844ec..0398a3f 100644 --- a/Guides/Compacted.md +++ b/Guides/Compacted.md @@ -37,8 +37,9 @@ extension Collection { 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. +has conditional conformance to `BidirectionalCollection` when the base +collection conforms, and both have conditional conformance to +`LazySequenceProtocol` when the base collection conforms. ### Naming diff --git a/Guides/Cycle.md b/Guides/Cycle.md index db7c485..4c9bbf2 100644 --- a/Guides/Cycle.md +++ b/Guides/Cycle.md @@ -26,20 +26,20 @@ Two new methods are added to collections: ```swift extension Collection { - func cycled() -> Cycle + func cycled() -> CycledSequence - func cycled(times: Int) -> FiniteCycle + func cycled(times: Int) -> CycledTimesCollection } ``` -The new `Cycle` type is a sequence only, given that the `Collection` protocol -design makes infinitely large types impossible/impractical. `Cycle` also -conforms to `LazySequenceProtocol` when the base type conforms. +The new `CycledSequence` type is a sequence only, given that the `Collection` +protocol design makes infinitely large types impossible/impractical. +`CycledSequence` also conforms to `LazySequenceProtocol` when the base type +conforms. -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. +The `CycledTimesCollection` type always has `Collection` conformance, with +`BidirectionalCollection`, `RandomAccessCollection`, and `LazySequenceProtocol` +conformance when the base type conforms. ### Complexity diff --git a/Guides/Indexed.md b/Guides/Indexed.md index 9d98d71..09d647c 100644 --- a/Guides/Indexed.md +++ b/Guides/Indexed.md @@ -21,15 +21,15 @@ for (i, n) in numbers.indexed() { ## Detailed Design -The `indexed` method returns an `Indexed` type: +The `indexed` method returns an `IndexedCollection` type: ```swift extension Collection { - func indexed() -> Indexed + func indexed() -> IndexedCollection } ``` -`Indexed` scales from a collection up to a random-access collection, depending on -its base type. `Indexed` also conforms to `LazySequenceProtocol` and -`LazyCollectionProtocol` when the base type conforms. +`IndexedCollection` scales from a collection up to a random-access collection, +depending on its base type. `Indexed` also conforms to `LazySequenceProtocol` +when the base type conforms. diff --git a/Guides/Intersperse.md b/Guides/Intersperse.md index ee5f91d..00c2b28 100644 --- a/Guides/Intersperse.md +++ b/Guides/Intersperse.md @@ -25,14 +25,14 @@ A new method is added to sequence: ```swift extension Sequence { - func interspersed(with separator: Element) -> Intersperse + func interspersed(with separator: Element) -> InterspersedSequence } ``` -The new `Intersperse` type represents the sequence when the separator is -inserted between each element. `Intersperse` conforms to `Collection`, -`BidirectionalCollection`, `RandomAccessCollection`, `LazySequenceProtocol` and -`LazyCollectionProtocol` when the base sequence conforms to those respective +The new `InterspersedSequence` type represents the sequence when the separator +is inserted between each element. `InterspersedSequence` conforms to +`Collection`, `BidirectionalCollection`, `RandomAccessCollection` and +`LazySequenceProtocol` when the base sequence conforms to those respective protocols. ### Complexity diff --git a/Guides/Joined.md b/Guides/Joined.md index 9b7a629..9b33126 100644 --- a/Guides/Joined.md +++ b/Guides/Joined.md @@ -70,8 +70,7 @@ Note that the sequence separator of the closure-less version defined on 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: +lazy sequences and collections for the same reason as explained above: ```swift extension LazySequenceProtocol where Element: Sequence { @@ -84,7 +83,7 @@ extension LazySequenceProtocol where Element: Sequence { ) -> JoinedByClosureSequence } -extension LazyCollectionProtocol where Element: Collection { +extension LazySequenceProtocol where Self: Collection, Element: Collection { public func joined( by separator: @escaping (Element, Element) -> Element.Element ) -> JoinedByClosureCollection> @@ -98,5 +97,4 @@ extension LazyCollectionProtocol where Element: Collection { `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. +conform to `BidirectionalCollection` when the base collection conforms. diff --git a/Guides/LazySplit.md b/Guides/LazySplit.md deleted file mode 100644 index 08bb1b7..0000000 --- a/Guides/LazySplit.md +++ /dev/null @@ -1,80 +0,0 @@ -# LazySplit - -[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/LazySplit.swift) | - [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/LazySplitTests.swift)] - -Lazily-evaluating versions of -[`split(maxSplits:omittingEmptySubsequences:whereSeparator:)`](https://developer.apple.com/documentation/swift/sequence/3128814-split) -and [`split(separator:maxSplits:omittingEmptySubsequences:)`](https://developer.apple.com/documentation/swift/sequence/3128818-split), -performing the same operation as their counterparts defined on -`Sequence` and `Collection`, are added to `LazySequence` and -`LazyCollection`. The `LazyCollection` methods allow splitting a -collection without allocating additional storage on the heap. - -```swift -// Splitting a lazy sequence. -let numbers = stride(from: 1, through: 16, by: 1) -for subsequence in numbers.lazy.split( - whereSeparator: { $0 % 3 == 0 || $0 % 5 == 0 } -) { - print(subsequence) -} -/* Prints: -[1, 2] -[4] -[7, 8] -[11] -[13, 14] -[16] -*/ - -// Splitting a lazy collection. -let line = "BLANCHE: I don't want realism. I want magic!" -for subsequence in line.lazy.split(separator: " ") { - print(subsequence) -} -/* Prints -BLANCHE: -I -don't -want -realism. -I -want -magic! -*/ -``` - -## Detailed Design - -`LazySequence` and `LazyCollection` are each extended with -`split(maxSplits:omittingEmptySubsequences:whereSeparator:)` and -`split(separator:maxSplits:omittingEmptySubsequences:)`. - -The `LazySequence` versions of those methods return an instance of -`LazySplitSequence`. The `LazyCollection` versions return an instance of -`LazySplitCollection`. - -`LazySplitSequence` wraps the sequence to be split, and provides an -iterator whose `next` method returns a newly-allocated array containing -the elements of each subsequence in the split sequence in turn. - -`LazySplitCollection` wraps the collection to be split. Its `Index` -wraps a range of base collection indices. `startIndex` is computed at -initialization. Subscripting a `LazySplitCollection` instance returns -the slice of the original collection which is the subsequence of the -split collection at the given index's position. - -### Complexity - -Iterating a `LazySplitSequence` instance is O(_n_) in time and space, -since each subsequence returned is a newly-allocated array. - -Iterating a `LazySplitCollection` instance is O(_n_) in time and O(1) in -space, since each subsequence returned is a slice of the base -collection. Since `startIndex` is computed at initialization, some or -all of the time cost may be paid at initialization. For example, if the -base collection contains no elements determined to be separators, it -will be iterated entirely on initialization of the split collection, and -all subsequent operations on the split collection, such as -`index(after:)`, will have complexity O(1). diff --git a/Guides/MinMax.md b/Guides/MinMax.md index 090d7a1..9cb5a74 100644 --- a/Guides/MinMax.md +++ b/Guides/MinMax.md @@ -3,9 +3,13 @@ [[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/MinMax.swift) | [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/MinMaxTests.swift)] -Returns the smallest or largest elements of this collection, sorted by a predicate or in the order defined by `Comparable` conformance. +Returns the smallest or largest elements of this collection, sorted by a +predicate or in the order defined by `Comparable` conformance. -If you need to sort a collection but only need access to a prefix or suffix of the sorted elements, using these methods can give you a performance boost over sorting the entire collection. The order of equal elements is guaranteed to be preserved. +If you need to sort a collection but only need access to a prefix or suffix of +the sorted elements, using these methods can give you a performance boost over +sorting the entire collection. The order of equal elements is guaranteed to be +preserved. ```swift let numbers = [7, 1, 6, 2, 8, 3, 9] @@ -13,9 +17,12 @@ 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. +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. +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] @@ -52,7 +59,8 @@ extension Sequence { } ``` -Additionally, versions of these methods for `Comparable` types are also provided: +Additionally, versions of these methods for `Comparable` types are also +provided: ```swift extension Collection where Element: Comparable { @@ -68,18 +76,34 @@ extension Sequence where Element: Comparable { ### 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 for minimal- or maximal-ordered subsets is based on +[Soroush Khanlou's research on this matter](https://khanlou.com/2018/12/analyzing-complexity/). +The total complexity is `O(k log k + nk)`, which will result in a runtime close +to `O(n)` if *k* is a small amount. If *k* is a large amount (more than 10% of +the collection), we fall back to sorting the entire array. Realistically, this +means the worst case is actually `O(n log n)`. -Here are some benchmarks we made that demonstrates how this implementation (SmallestM) behaves when *k* increases (before implementing the fallback): +Here are some benchmarks we made that demonstrates how this implementation +(SmallestM) behaves when *k* increases (before implementing the fallback): ![Benchmark](Resources/SortedPrefix/FewElements.png) ![Benchmark 2](Resources/SortedPrefix/ManyElements.png) -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. +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 `` 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 `` library defines a `partial_sort` function where the +entire array is returned using a partial heap sort. It also defines a +`minmax_element` function that scans a range for its minimal and maximal +elements. -**Python:** Defines a `heapq` priority queue that can be used to manually achieve the same result. +**Python:** Defines a `heapq` priority queue that can be used to manually +achieve the same result. diff --git a/Guides/Permutations.md b/Guides/Permutations.md index 7c1d759..6080a0c 100644 --- a/Guides/Permutations.md +++ b/Guides/Permutations.md @@ -98,19 +98,20 @@ for perm in numbers.permutations(ofCount: 0...) { ## Detailed Design -The `permutations(ofCount:)` and `uniquePermutations(ofCount:)` methods are declared as `Collection` extensions, -and return `Permutations` and `UniquePermutations` instances, respectively: +The `permutations(ofCount:)` and `uniquePermutations(ofCount:)` methods are +declared as `Collection` extensions, and return `PermutationsSequence` and +`UniquePermutationsSequence` instances, respectively: ```swift extension Collection { - public func permutations(ofCount k: Int? = nil) -> Permutations - public func permutations(ofCount kRange: R) -> Permutations + public func permutations(ofCount k: Int? = nil) -> PermutationsSequence + public func permutations(ofCount kRange: R) -> PermutationsSequence where R: RangeExpression, R.Bound == Int } extension Collection where Element: Hashable { - public func uniquePermutations(ofCount k: Int? = nil) -> UniquePermutations - public func uniquePermutations(ofCount kRange: R) -> UniquePermutations + public func uniquePermutations(ofCount k: Int? = nil) -> UniquePermutationsSequence + public func uniquePermutations(ofCount kRange: R) -> UniquePermutationsSequence where R: RangeExpression, R.Bound == Int } ``` @@ -119,18 +120,19 @@ Since both result types need to store an array of the collection’s indices and mutate the array to generate each permutation, they only have `Sequence` conformance. Adding `Collection` conformance would require storing the array in the index type, which would in turn lead to copying the -array at every index advancement. The `Permutations` type -conforms to `LazySequenceProtocol` when its base type conforms. +array at every index advancement. The `PermutationsSequence` and +`UniquePermutationsSequence` types conforms to `LazySequenceProtocol` when their +base type conforms. ### Complexity Calling `permutations()` is an O(1) operation. Creating the iterator for a -`Permutations` instance and each call to `Permutations.Iterator.next()` is an -O(_n_) operation. +`PermutationsSequence` instance and each call to +`PermutationsSequence.Iterator.next()` is an O(_n_) operation. -Calling `uniquePermutations()` is an O(_n_) operation, because it preprocesses the -collection to find duplicate elements. Creating the iterator for and each call to -`next()` is also an O(_n_) operation. +Calling `uniquePermutations()` is an O(_n_) operation, because it preprocesses +the collection to find duplicate elements. Creating the iterator for and each +call to `next()` is also an O(_n_) operation. ### Naming diff --git a/Guides/Product.md b/Guides/Product.md index dcda409..6271107 100644 --- a/Guides/Product.md +++ b/Guides/Product.md @@ -25,26 +25,26 @@ When either collection is empty, the resulting wrapper collection is also empty. ## Detailed Design The `product` function takes (at minimum) a sequence and a collection and -returns a `Product2` type: +returns a `Product2Sequence` type: ```swift public func product( _ s1: Base1, _ s2: Base2 -) -> Product2 +) -> Product2Sequence ``` We require `Collection` conformance for `Base2`, since it needs to be iterated over multiple times. `Base1`, by contrast, is only iterated over a single time, so it can be a sequence. -The `Product2` type wraps the base sequence and collection, and acts as a -sequence in the base case, upgrading to a collection, a bidirectional +The `Product2Sequence` type wraps the base sequence and collection, and acts as +a sequence in the base case, upgrading to a collection, a bidirectional collection, and a random-access collection when both base collections have those conformances. -We don't provide higher arities (like `Product3`, `Product4`, etc.) at this -time to match the standard library's `Zip2` type. Users can compose multiple -calls to `product` if they would like higher arities. +We don't provide higher arities (like `Product3Sequence`, `Product4Sequence`, +etc.) at this time to match the standard library's `Zip2Sequence` type. Users +can compose multiple calls to `product` if they would like higher arities. ### Complexity diff --git a/Guides/RandomSampling.md b/Guides/RandomSampling.md index 17595cd..753e023 100644 --- a/Guides/RandomSampling.md +++ b/Guides/RandomSampling.md @@ -17,7 +17,7 @@ source.randomSample(count: 4) // e.g. [30, 10, 70, 50] source.randomStableSample(count: 4) // e.g. [20, 30, 80, 100] -// + var rng = SplitMix64(seed: 0) source.randomSample(count: 4, using: &rng) ``` @@ -146,4 +146,4 @@ performance characteristics as the collection itself, so a user can call The stable version of sampling could theoretically return a lazy wrapper instead of eagerly creating the sample. However, this isn’t well-motivated and poses some challenges, such as needing to store a copy of the random generator -and potentially needing to cache the randomly-generated values. \ No newline at end of file +and potentially needing to cache the randomly-generated values. diff --git a/Guides/Reductions.md b/Guides/Reductions.md index fa93bde..126ed6e 100644 --- a/Guides/Reductions.md +++ b/Guides/Reductions.md @@ -3,7 +3,8 @@ [[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Reductions.swift) | [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/ReductionsTests.swift)] -Produces all the intermediate results of reducing a sequence's elements using a closure. +Produces all the intermediate results of reducing a sequence's elements using a +closure. ```swift let exclusiveRunningTotal = (1...5).reductions(0, +) @@ -26,39 +27,37 @@ sequence and another trio are added to `Sequence` which are eagerly evaluated. ```swift extension LazySequenceProtocol { + public func reductions( + _ initial: Result, + _ transform: @escaping (Result, Element) -> Result + ) -> ExclusiveReductionsSequence - public func reductions( - _ initial: Result, - _ transform: @escaping (Result, Element) -> Result - ) -> ExclusiveReductions + public func reductions( + into initial: Result, + _ transform: @escaping (inout Result, Element) -> Void + ) -> ExclusiveReductionsSequence - public func reductions( - into initial: Result, - _ transform: @escaping (inout Result, Element) -> Void - ) -> ExclusiveReductions - - public func reductions( - _ transform: @escaping (Element, Element) -> Element - ) -> InclusiveReductions + public func reductions( + _ transform: @escaping (Element, Element) -> Element + ) -> InclusiveReductionsSequence } ``` ```swift extension Sequence { + public func reductions( + _ initial: Result, + _ transform: (Result, Element) throws -> Result + ) rethrows -> [Result] - public func reductions( - _ initial: Result, - _ transform: (Result, Element) throws -> Result - ) rethrows -> [Result] + public func reductions( + into initial: Result, + _ transform: (inout Result, Element) throws -> Void + ) rethrows -> [Result] - public func reductions( - into initial: Result, - _ transform: (inout Result, Element) throws -> Void - ) rethrows -> [Result] - - public func reductions( - _ transform: (Element, Element) throws -> Element - ) rethrows -> [Element] + public func reductions( + _ transform: (Element, Element) throws -> Element + ) rethrows -> [Element] } ``` @@ -102,7 +101,7 @@ takes an initial value to use for the first element in the returned sequence, and another which uses the first value of the base sequence as the initial value. C++ calls these variants exclusive and inclusive respectively and so these terms carry through as the name for the lazy sequences; -`ExclusiveReductions` and `InclusiveReductions`. +`ExclusiveReductionsSequence` and `InclusiveReductionsSequence`. [SE-0045]: https://forums.swift.org/t/review-se-0045-add-scan-prefix-while-drop-while-and-iterate-to-the-stdlib/2382 [Issue 25]: https://github.com/apple/swift-algorithms/issues/25 diff --git a/Guides/Split.md b/Guides/Split.md new file mode 100644 index 0000000..db97306 --- /dev/null +++ b/Guides/Split.md @@ -0,0 +1,79 @@ +# Split + +[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Split.swift) | + [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/SplitTests.swift)] + +Lazily-evaluating versions of +[`split(maxSplits:omittingEmptySubsequences:whereSeparator:)`](https://developer.apple.com/documentation/swift/sequence/3128814-split) +and [`split(separator:maxSplits:omittingEmptySubsequences:)`](https://developer.apple.com/documentation/swift/sequence/3128818-split), +performing the same operation as their counterparts defined on +`Sequence` and `Collection`, are added to `LazySequence` and +`LazyCollection`. The `LazyCollection` methods allow splitting a +collection without allocating additional storage on the heap. + +```swift +// Splitting a lazy sequence. +let numbers = stride(from: 1, through: 16, by: 1) +for subsequence in numbers.lazy.split( + whereSeparator: { $0 % 3 == 0 || $0 % 5 == 0 } +) { + print(subsequence) +} +/* Prints: +[1, 2] +[4] +[7, 8] +[11] +[13, 14] +[16] +*/ + +// Splitting a lazy collection. +let line = "BLANCHE: I don't want realism. I want magic!" +for subsequence in line.lazy.split(separator: " ") { + print(subsequence) +} +/* Prints +BLANCHE: +I +don't +want +realism. +I +want +magic! +*/ +``` + +## Detailed Design + +`LazySequence` and `LazyCollection` are each extended with +`split(maxSplits:omittingEmptySubsequences:whereSeparator:)` and +`split(separator:maxSplits:omittingEmptySubsequences:)`. + +The `LazySequence` versions of those methods return an instance of +`SplitSequence`. The `LazyCollection` versions return an instance of +`SplitCollection`. + +`SplitSequence` wraps the sequence to be split, and provides an iterator whose +`next` method returns a newly-allocated array containing the elements of each +subsequence in the split sequence in turn. + +`SplitCollection` wraps the collection to be split. Its `Index` wraps a range of +base collection indices. `startIndex` is computed at initialization. +Subscripting a `SplitCollection` instance returns the slice of the original +collection which is the subsequence of the split collection at the given index's +position. + +### Complexity + +Iterating a `SplitSequence` instance is O(_n_) in time and space, since each +subsequence returned is a newly-allocated array. + +Iterating a `SplitCollection` instance is O(_n_) in time and O(1) in space, +since each subsequence returned is a slice of the base collection. Since +`startIndex` is computed at initialization, some or all of the time cost may be +paid at initialization. For example, if the base collection contains no elements +determined to be separators, it will be iterated entirely on initialization of +the split collection, and all subsequent operations on the split collection, +such as `index(after:)`, will have complexity O(1). diff --git a/Guides/Stride.md b/Guides/Stride.md index a309f25..7eb9e7f 100644 --- a/Guides/Stride.md +++ b/Guides/Stride.md @@ -3,7 +3,7 @@ [[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Stride.swift) | [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/StrideTests.swift)] -A type that steps over sequence elements by the specified amount. +Step over the elements of a sequence elements by a specified amount. This is available through the `striding(by:)` method on any `Sequence`. @@ -11,33 +11,39 @@ This is available through the `striding(by:)` method on any `Sequence`. (0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10] ``` -If the stride is larger than the count, the resulting wrapper only contains the -first element. +If the stride is larger than the length of the sequence, the resulting wrapper +only contains the first element. The stride amount must be a positive value. ## Detailed Design -The `striding(by:)` method is declared as a `Sequence` extension, and returns a -`Stride` type: +The `striding(by:)` method is declared in extension of both `Sequence` and +`Collection`: ```swift extension Sequence { - public func striding(by step: Int) -> Stride + public func striding(by step: Int) -> StridingSequence +} + +extension Collection { + public func striding(by step: Int) -> StridingCollection } ``` -A custom `Index` type is defined so that it's not possible to get confused when trying -to access an index of the stride collection. +The reason for this distinction is subtle. The `StridingSequence.Iterator` type +is unable to skip over multiple elements of the wrapped iterator at once since +that's not part of `IteratorProtocol`'s interface. In order to efficiently +stride over collections that provide a fast way of skipping multiple elements at +once, the `StridingCollection` type was added which does not provide a custom +`Iterator` type and therefore always strides over the underlying collection in +the fastest way possible. See the related +[GitHub issue](https://github.com/apple/swift-algorithms/issues/63) for more +information. -```swift -[0, 1, 2, 3, 4].striding(by: 2)[1] // == 1 -[0, 1, 2, 3, 4].striding(by: 2).map { $0 }[1] // == 2 -``` - -A careful thought was given to the composition of these strides by giving a custom -implementation to `index(_:offsetBy:limitedBy)` which multiplies the offset by the -stride amount. +A careful thought was given to the composition of these strides by giving a +custom implementation to `index(_:offsetBy:limitedBy)` which multiplies the +offset by the stride amount. ```swift base.index(i.base, offsetBy: distance * stride, limitedBy: base.endIndex) @@ -52,8 +58,9 @@ The following two lines of code are equivalent, including performance: ### Complexity -The call to `striding(by: k)` is always O(_1_) and access to the next value in the stride -is O(_1_) if the collection conforms to `RandomAccessCollection`, otherwise O(_k_). +The call to `striding(by: k)` is always O(_1_) and access to the next value in +the stride is O(_1_) if the collection conforms to `RandomAccessCollection`, +otherwise O(_k_). ### Comparison with other languages diff --git a/Guides/Suffix.md b/Guides/Suffix.md index 180cc13..f772f3c 100644 --- a/Guides/Suffix.md +++ b/Guides/Suffix.md @@ -3,37 +3,37 @@ [[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Suffix.swift) | [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/SuffixTests.swift)] +This function returns a subsequence containing the elements from the end of the +collection until predicate returns `false` and skipping the remaining elements. -This function returns a subsequence containing the elements from the end of the collection until predicate returns `false` and skipping the remaining elements. - -This example uses `suffix(while: )` to iterate through collection of integers from the end until the predicate returns false, in this case when `$0 <= 5` +This example uses `suffix(while: )` to iterate through collection of integers +from the end until the predicate returns false, in this case when `$0 <= 5` ```swift (0...10).suffix(while: { $0 > 5 } // == [6,7,8,9,10] ``` - ## Detailed Design -The `suffix(while:)` function is added as a method on an extension of `BidirectionalCollection`. - +The `suffix(while:)` function is added as a method on an extension of +`BidirectionalCollection`. ```swift extension BidirectionalCollection { - - public func suffix(while predicate: (Element) throws -> Bool) rethrows -> SubSequence + public func suffix(while predicate: (Element) throws -> Bool) rethrows -> SubSequence } ``` -This method requires `BidirectionalCollection` for an efficient implementation which visits as few elements as possible. Swift's protocol allows for backward traversal of a collection as well as access to *last* property of a collection. +This method requires `BidirectionalCollection` for an efficient implementation +which visits as few elements as possible. Swift's protocol allows for backward +traversal of a collection as well as access to *last* property of a collection. ### Complexity Calling this method is O(*n*), where *n* is the length of the collection. - ### Naming -The function's name resembles that of an existing Swift function `prefix(while:)`, which performs same operation however in the forward direction of the collection. Hence, as this function traverses from the end of the collection, `suffix(while:)` is an appropriate name. - - - +The function's name resembles that of an existing Swift function +`prefix(while:)`, which performs same operation however in the forward direction +of the collection. Hence, as this function traverses from the end of the +collection, `suffix(while:)` is an appropriate name. diff --git a/Guides/Trim.md b/Guides/Trim.md index 11b1c4b..4eef4e5 100644 --- a/Guides/Trim.md +++ b/Guides/Trim.md @@ -3,10 +3,11 @@ [[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Trim.swift) | [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/TrimTests.swift)] -Returns a `SubSequence` formed by discarding all elements at the start and end of the collection -which satisfy the given predicate. +Returns a `SubSequence` formed by discarding all elements at the start and end +of the collection which satisfy the given predicate. -This example uses `trimming(while:)` to get a substring without the white space at the beginning and end of the string. +This example uses `trimming(while:)` to get a substring without the white space +at the beginning and end of the string. ```swift let myString = " hello, world " @@ -22,37 +23,42 @@ A new method is added to `BidirectionalCollection`: ```swift extension BidirectionalCollection { - - public func trimming(while predicate: (Element) throws -> Bool) rethrows -> SubSequence + public func trimming(while predicate: (Element) throws -> Bool) rethrows -> SubSequence } ``` -This method requires `BidirectionalCollection` for an efficient implementation which visits as few elements as possible. +This method requires `BidirectionalCollection` for an efficient implementation +which visits as few elements as possible. -A less-efficient implementation is _possible_ for any `Collection`, which would involve always traversing the -entire collection. This implementation is not provided, as it would mean developers of generic algorithms who forget -to add the `BidirectionalCollection` constraint will receive that inefficient implementation: +A less-efficient implementation is _possible_ for any `Collection`, which would +involve always traversing the entire collection. This implementation is not +provided, as it would mean developers of generic algorithms who forget to add +the `BidirectionalCollection` constraint will receive that inefficient +implementation: ```swift func myAlgorithm(input: Input) where Input: Collection { - - let trimmedInput = input.trimming(while: { ... }) // Uses least-efficient implementation. + let trimmedInput = input.trimming(while: { ... }) // Uses least-efficient implementation. } func myAlgorithm2(input: Input) where Input: BidirectionalCollection { - - let trimmedInput = input.trimming(while: { ... }) // Uses most-efficient implementation. + let trimmedInput = input.trimming(while: { ... }) // Uses most-efficient implementation. } ``` -Swift provides the `BidirectionalCollection` protocol for marking types which support reverse traversal, -and generic types and algorithms which want to make use of that should add it to their constraints. +Swift provides the `BidirectionalCollection` protocol for marking types which +support reverse traversal, and generic types and algorithms which want to make +use of that should add it to their constraints. ### >= 0.3.0 -In `v0.3.0` new methods are added to allow discarding all the elements matching the predicate at the beginning (prefix) or at the ending (suffix) of the collection. -- `trimmingSuffix(while:)` can only be run on collections conforming to the `BidirectionalCollection` protocol. -- `trimmingPrefix(while:)` can be run also on collections conforming to the `Collection` protocol. +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 " @@ -60,7 +66,8 @@ 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. +Also mutating variants for all the methods already existing and the new ones are +added. ```swift var myString = " hello, world " myString.trim(while: \.isWhitespace) @@ -73,7 +80,8 @@ Calling this method is O(_n_). ### Naming -The name `trim` has precedent in other programming languages. Another popular alternative might be `strip`. +The name `trim` has precedent in other programming languages. Another popular +alternative might be `strip`. | Example usage | Languages | |-|-| @@ -98,30 +106,38 @@ The name `trim` has precedent in other programming languages. Another popular al | TRIM(''string'') | SQL | | String.trim ''string'' | OCaml 4+ | -Note: This is an abbreviated list from Wikipedia. [Full table](https://en.wikipedia.org/wiki/Comparison_of_programming_languages_(string_functions)#trim) +Note: This is an abbreviated list from Wikipedia. +[Full table](https://en.wikipedia.org/wiki/Comparison_of_programming_languages_(string_functions)#trim) -The standard library includes a variety of methods which perform similar operations: +The standard library includes a variety of methods which perform similar +operations: -- Firstly, there are `dropFirst(Int)` and `dropLast(Int)`. These return slices but do not support user-defined predicates. - If the collection's `count` is less than the number of elements to drop, they return an empty slice. -- Secondly, there is `drop(while:)`, which also returns a slice and is equivalent to a 'left-trim' (trimming from the head but not the tail). - If the entire collection is dropped, this method returns an empty slice. -- Thirdly, there are `removeFirst(Int)` and `removeLast(Int)` which do not return slices and actually mutate the collection. - If the collection's `count` is less than the number of elements to remove, this method triggers a runtime error. -- Lastly, there are the `popFirst()` and `popLast()` methods, which work like `removeFirst()` and `removeLast()`, - except they do not trigger a runtime error for empty collections. +- Firstly, there are `dropFirst(Int)` and `dropLast(Int)`. These return slices +but do not support user-defined predicates. If the collection's `count` is less +than the number of elements to drop, they return an empty slice. +- Secondly, there is `drop(while:)`, which also returns a slice and is +equivalent to a 'left-trim' (trimming from the head but not the tail). If the +entire collection is dropped, this method returns an empty slice. +- Thirdly, there are `removeFirst(Int)` and `removeLast(Int)` which do not +return slices and actually mutate the collection. If the collection's `count` is +less than the number of elements to remove, this method triggers a runtime +error. +- Lastly, there are the `popFirst()` and `popLast()` methods, which work like +`removeFirst()` and `removeLast()`, except they do not trigger a runtime error +for empty collections. -The closest neighbours to this function would be the `drop` family of methods. Unfortunately, unlike `dropFirst(Int)`, -the name `drop(while:)` does not specify which end(s) of the collection it operates on. Moreover, one could easily +The closest neighbours to this function would be the `drop` family of methods. +Unfortunately, unlike `dropFirst(Int)`,the name `drop(while:)` does not specify +which end(s) of the collection it operates on. Moreover, one could easily mistake code such as: ```swift let result = myString.drop(while: \.isWhitespace) ``` -With a lazy filter that drops _all_ whitespace characters regardless of where they are in the string. -Besides that, the root `trim` leads to clearer, more concise code, which is more aligned with other programming -languages: +With a lazy filter that drops _all_ whitespace characters regardless of where +they are in the string. Besides that, the root `trim` leads to clearer, more +concise code, which is more aligned with other programming languages: ```swift // Does `result` contain the input, trimmed of certain elements? @@ -130,4 +146,4 @@ let result = input.dropFromBothEnds(while: { ... }) // No such ambiguity here. let result = input.trimming(while: { ... }) -``` \ No newline at end of file +``` diff --git a/Guides/Unique.md b/Guides/Unique.md index 13de268..67e4377 100644 --- a/Guides/Unique.md +++ b/Guides/Unique.md @@ -5,10 +5,9 @@ Methods to strip repeated elements from a sequence or collection. -The `uniqued()` method returns a sequence, dropping duplicate elements -from a sequence. The `uniqued(on:)` method does the same, using -the result of the given closure to determine the "uniqueness" of each -element. +The `uniqued()` method returns a sequence, dropping duplicate elements from a +sequence. The `uniqued(on:)` method does the same, using the result of the given +closure to determine the "uniqueness" of each element. ```swift let numbers = [1, 2, 3, 3, 2, 3, 3, 2, 2, 2, 1] @@ -19,14 +18,14 @@ let unique = numbers.uniqued() ## 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`. +Both methods are available for sequences, with the simplest limited to when the +element type conforms to `Hashable`. Both methods preserve the relative order of +the elements. `uniqued(on:)` has a matching lazy version that is added to +`LazySequenceProtocol`. ```swift extension Sequence where Element: Hashable { - func uniqued() -> Uniqued + func uniqued() -> UniquedSequence } extension Sequence { @@ -35,15 +34,15 @@ extension Sequence { } extension LazySequenceProtocol { - func uniqued(on projection: @escaping (Element) -> Subject) -> Uniqued + func uniqued(on projection: @escaping (Element) -> Subject) -> UniquedSequence where Subject: Hashable } ``` ### Complexity -The eager `uniqued(on:)` method is O(_n_) in both time and space complexity. -The lazy versions are O(_1_). +The eager `uniqued(on:)` method is O(_n_) in both time and space complexity. The +lazy versions are O(_1_). ### Comparison with other languages diff --git a/Guides/Windows.md b/Guides/Windows.md index 6b2d1fd..13e52cc 100644 --- a/Guides/Windows.md +++ b/Guides/Windows.md @@ -6,7 +6,9 @@ Break a collection into overlapping subsequences where elements are slices from the original collection. -The `windows(ofCount:)` method takes a size as a parameter and returns a collection of subsequences. Each element of the returned collection is a successive overlapping slice of the given size. +The `windows(ofCount:)` method takes a size as a parameter and returns a +collection of subsequences. Each element of the returned collection is a +successive overlapping slice of the given size. ```swift let swift = "swift" @@ -21,24 +23,26 @@ The `windows(ofCount:)` method is added as an extension `Collection` method: ```swift extension Collection { - public func windows(ofCount count: Int) -> Windows + public func windows(ofCount count: Int) -> WindowsOfCountCollection } ``` -If a size larger than the collection's length is specified, the returned collection is empty. +If a size larger than the collection's length is specified, the returned +collection is empty. ```swift [1, 2, 3].windows(ofCount: 5).isEmpty // true ``` -The resulting `Windows` type is a collection, with conditional conformance to the -`BidirectionalCollection`, `RandomAccessCollection`, and -`LazyCollectionProtocol` protocols when the base collection conforms. +The resulting `WindowsOfCountCollection` type is a collection, with conditional +conformance to the `BidirectionalCollection`, `RandomAccessCollection`, and +`LazySequenceProtocol` protocols when the base collection conforms. ### Complexity The call to `windows(ofCount: k)` is O(1) if the collection conforms to -`RandomAccessCollection`, otherwise O(_k_). Access to each successive window is O(1). +`RandomAccessCollection`, otherwise O(_k_). Access to each successive window is +O(1). ### Naming @@ -51,5 +55,5 @@ and `permutations(ofCount:)`. ### Comparison with other languages [rust](https://doc.rust-lang.org/std/slice/struct.Windows.html) has -`std::slice::Windows` which is a method available on slices. It has the same +`std::slice::Windows` which is a method available on slices. It has the same semantics as described here. diff --git a/Package.swift b/Package.swift index b9e8f90..5993f0a 100644 --- a/Package.swift +++ b/Package.swift @@ -20,13 +20,13 @@ let package = Package( targets: ["Algorithms"]), ], dependencies: [ - .package(url: "https://github.com/apple/swift-numerics", from: "0.0.1"), + .package(url: "https://github.com/apple/swift-numerics", from: "1.0.0"), ], targets: [ .target( name: "Algorithms", dependencies: [ - .product(name: "Numerics", package: "swift-numerics"), + .product(name: "RealModule", package: "swift-numerics"), ]), .testTarget( name: "SwiftAlgorithmsTests", diff --git a/README.md b/README.md index c5bc98d..ce07182 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ Read more about the package, and the intent behind it, in the [announcement on s - [`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. +- [`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. ## Adding Swift Algorithms as a Dependency @@ -57,32 +57,25 @@ To use the `Algorithms` library in a SwiftPM project, add the following line to the dependencies in your `Package.swift` file: ```swift -.package(url: "https://github.com/apple/swift-algorithms", from: "0.0.1"), +.package(url: "https://github.com/apple/swift-algorithms", from: "1.0.0"), ``` -Because `Algorithms` is under active development, -source-stability is only guaranteed within minor versions (e.g. between `0.0.3` and `0.0.4`). -If you don't want potentially source-breaking package updates, -use this dependency specification instead: +Include `"Algorithms"` as a dependency for your executable target: ```swift -.package(url: "https://github.com/apple/swift-algorithms", .upToNextMinor(from: "0.1.0")), +.target(name: "", dependencies: [ + .product(name: "Algorithms", package: "swift-algorithms"), +]), ``` -Finally, include `"Algorithms"` as a dependency for your executable target: +Finally, add `import Algorithms` to your source code. -```swift -let package = Package( - // name, platforms, products, etc. - dependencies: [ - .package(url: "https://github.com/apple/swift-algorithms", from: "0.1.0"), - // other dependencies - ], - targets: [ - .target(name: "", dependencies: [ - .product(name: "Algorithms", package: "swift-algorithms"), - ]), - // other targets - ] -) -``` +## Source Stability + +The Swift Numerics package is source stable; version numbers follow [Semantic Versioning](https://semver.org/). Source breaking changes to public API can only land in a new major version. + +The public API of version 1.0 of the `swift-algorithms` package consists of non-underscored declarations that are marked `public` in the `Algorithms` module. Interfaces that aren't part of the public API may continue to change in any release, including patch releases. + +Future minor versions of the package may introduce changes to these rules as needed. + +We'd like this package to quickly embrace Swift language and toolchain improvements that are relevant to its mandate. Accordingly, from time to time, we expect that new versions of this package will require clients to upgrade to a more recent Swift toolchain release. Requiring a new Swift release will only require a minor version bump. diff --git a/Sources/Algorithms/AdjacentPairs.swift b/Sources/Algorithms/AdjacentPairs.swift index 002a07a..1c1fd71 100644 --- a/Sources/Algorithms/AdjacentPairs.swift +++ b/Sources/Algorithms/AdjacentPairs.swift @@ -14,9 +14,8 @@ extension 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: + /// sequence. The following example uses the `adjacentPairs()` method to + /// iterate over adjacent pairs of integers: /// /// for pair in (1...).prefix(5).adjacentPairs() { /// print(pair) @@ -69,7 +68,8 @@ public struct AdjacentPairsSequence { } extension AdjacentPairsSequence { - /// The iterator for an `AdjacentPairsSequence` or `AdjacentPairsCollection`. + /// The iterator for an `AdjacentPairsSequence` or `AdjacentPairsCollection` + /// instance. public struct Iterator { @usableFromInline internal var base: Base.Iterator @@ -126,44 +126,20 @@ public struct AdjacentPairsCollection { @usableFromInline internal let base: Base - public let startIndex: Index + @usableFromInline + internal let secondBaseIndex: Base.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) + self.secondBaseIndex = base.isEmpty + ? base.endIndex + : base.index(after: base.startIndex) } } extension AdjacentPairsCollection { - public typealias Iterator = AdjacentPairsSequence.Iterator - - @inlinable - public func makeIterator() -> Iterator { - Iterator(base: base.makeIterator()) - } -} - -extension AdjacentPairsCollection { - /// A position in an `AdjacentPairsCollection`. + /// A position in an `AdjacentPairsCollection` instance. public struct Index: Comparable { @usableFromInline internal var first: Base.Index @@ -178,7 +154,7 @@ extension AdjacentPairsCollection { } @inlinable - public static func ==(lhs: Index, rhs: Index) -> Bool { + public static func == (lhs: Index, rhs: Index) -> Bool { lhs.first == rhs.first } @@ -190,6 +166,13 @@ extension AdjacentPairsCollection { } extension AdjacentPairsCollection: Collection { + @inlinable + public var startIndex: Index { + Index( + first: secondBaseIndex == base.endIndex ? base.endIndex : base.startIndex, + second: secondBaseIndex) + } + @inlinable public var endIndex: Index { Index(first: base.endIndex, second: base.endIndex) @@ -305,7 +288,7 @@ extension AdjacentPairsCollection: RandomAccessCollection where Base: RandomAccessCollection {} extension AdjacentPairsCollection: LazySequenceProtocol, LazyCollectionProtocol - where Base: LazyCollectionProtocol {} + where Base: LazySequenceProtocol {} extension AdjacentPairsCollection.Index: Hashable where Base.Index: Hashable { @inlinable diff --git a/Sources/Algorithms/Chain.swift b/Sources/Algorithms/Chain.swift index 57dee3a..572050e 100644 --- a/Sources/Algorithms/Chain.swift +++ b/Sources/Algorithms/Chain.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// /// A concatenation of two sequences with the same element type. -public struct Chain2 +public struct Chain2Sequence where Base1.Element == Base2.Element { /// The first sequence in this chain. @@ -28,8 +28,8 @@ public struct Chain2 } } -extension Chain2: Sequence { - /// The iterator for a `Chain2` sequence. +extension Chain2Sequence: Sequence { + /// The iterator for a `Chain2Sequence` instance. public struct Iterator: IteratorProtocol { @usableFromInline internal var iterator1: Base1.Iterator @@ -38,7 +38,7 @@ extension Chain2: Sequence { internal var iterator2: Base2.Iterator @inlinable - internal init(_ concatenation: Chain2) { + internal init(_ concatenation: Chain2Sequence) { iterator1 = concatenation.base1.makeIterator() iterator2 = concatenation.base2.makeIterator() } @@ -55,8 +55,8 @@ extension Chain2: Sequence { } } -extension Chain2: Collection where Base1: Collection, Base2: Collection { - /// A position in a `Chain2` collection. +extension Chain2Sequence: Collection where Base1: Collection, Base2: Collection { + /// A position in a `Chain2Sequence` instance. public struct Index: Comparable { // The internal index representation, which can either be an index of the // first collection or the second. The `endIndex` of the first collection @@ -64,7 +64,7 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection { // from the penultimate index of the first collection to the start of the // second. @usableFromInline - internal enum Representation : Equatable { + internal enum Representation: Equatable { case first(Base1.Index) case second(Base2.Index) } @@ -115,7 +115,7 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection { @inlinable public var endIndex: Index { - return Index(second: base2.endIndex) + Index(second: base2.endIndex) } @inlinable @@ -263,7 +263,7 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection { } } -extension Chain2: BidirectionalCollection +extension Chain2Sequence: BidirectionalCollection where Base1: BidirectionalCollection, Base2: BidirectionalCollection { @inlinable @@ -280,7 +280,7 @@ extension Chain2: BidirectionalCollection } } -extension Chain2: RandomAccessCollection +extension Chain2Sequence: RandomAccessCollection where Base1: RandomAccessCollection, Base2: RandomAccessCollection {} //===----------------------------------------------------------------------===// @@ -314,20 +314,6 @@ extension Chain2: RandomAccessCollection /// /// - Complexity: O(1) @inlinable -public func chain(_ s1: S1, _ s2: S2) -> Chain2 { - Chain2(base1: s1, base2: s2) -} - -// MARK: - Deprecations - -@available(*, deprecated, renamed: "Chain2") -public typealias Chain = Chain2 - -extension Sequence { - @available(*, deprecated, message: "Use the chain(_:_:) function, instead.") - public func chained(with other: S) -> Chain2 - where Element == S.Element - { - Chain2(base1: self, base2: other) - } +public func chain(_ s1: S1, _ s2: S2) -> Chain2Sequence { + Chain2Sequence(base1: s1, base2: s2) } diff --git a/Sources/Algorithms/Chunked.swift b/Sources/Algorithms/Chunked.swift index 883ecf3..850ec25 100644 --- a/Sources/Algorithms/Chunked.swift +++ b/Sources/Algorithms/Chunked.swift @@ -13,7 +13,7 @@ /// predicate. /// /// Call `lazy.chunked(by:)` on a collection to create an instance of this type. -public struct ChunkedBy { +public struct ChunkedByCollection { /// The collection that this instance provides a view onto. @usableFromInline internal let base: Base @@ -26,9 +26,9 @@ public struct ChunkedBy { @usableFromInline internal let belongInSameGroup: (Subject, Subject) -> Bool - /// The upper bound of the first chunk. + /// The end index of the first chunk. @usableFromInline - internal var firstUpperBound: Base.Index + internal var endOfFirstChunk: Base.Index @inlinable internal init( @@ -39,15 +39,15 @@ public struct ChunkedBy { self.base = base self.projection = projection self.belongInSameGroup = belongInSameGroup - self.firstUpperBound = base.startIndex + self.endOfFirstChunk = base.startIndex if !base.isEmpty { - firstUpperBound = endOfChunk(startingAt: base.startIndex) + endOfFirstChunk = endOfChunk(startingAt: base.startIndex) } } } -extension ChunkedBy: LazyCollectionProtocol { +extension ChunkedByCollection: Collection { /// A position in a chunked collection. public struct Index: Comparable { /// The range corresponding to the chunk at this position. @@ -88,7 +88,7 @@ extension ChunkedBy: LazyCollectionProtocol { @inlinable public var startIndex: Index { - Index(base.startIndex.. = ChunkedBy - -@available(*, deprecated, renamed: "ChunkedBy") -public typealias Chunked = ChunkedBy +extension ChunkedByCollection: LazyCollectionProtocol {} /// A collection wrapper that breaks a collection into chunks based on a /// predicate. /// /// Call `lazy.chunked(on:)` on a collection to create an instance of this type. -public struct ChunkedOn { +public struct ChunkedOnCollection { @usableFromInline - internal var chunked: ChunkedBy + internal var chunked: ChunkedByCollection @inlinable internal init( base: Base, - projection: @escaping (Base.Element) -> Subject, - belongInSameGroup: @escaping (Subject, Subject) -> Bool + projection: @escaping (Base.Element) -> Subject ) { - self.chunked = ChunkedBy(base: base, projection: projection, belongInSameGroup: belongInSameGroup) + self.chunked = ChunkedByCollection( + base: base, + projection: projection, + belongInSameGroup: ==) } } -extension ChunkedOn: LazyCollectionProtocol { - public typealias Index = ChunkedBy.Index +extension ChunkedOnCollection: Collection { + public typealias Index = ChunkedByCollection.Index @inlinable public var startIndex: Index { @@ -189,17 +187,22 @@ extension ChunkedOn: LazyCollectionProtocol { } } -extension ChunkedOn: BidirectionalCollection where Base: BidirectionalCollection { +extension ChunkedOnCollection: BidirectionalCollection + where Base: BidirectionalCollection +{ + @inlinable public func index(before i: Index) -> Index { chunked.index(before: i) } } +extension ChunkedOnCollection: LazyCollectionProtocol {} + //===----------------------------------------------------------------------===// // lazy.chunked(by:) / lazy.chunked(on:) //===----------------------------------------------------------------------===// -extension LazyCollectionProtocol { +extension LazySequenceProtocol where Self: Collection, Elements: Collection { /// Returns a lazy collection of subsequences of this collection, chunked by /// the given predicate. /// @@ -207,8 +210,8 @@ extension LazyCollectionProtocol { @inlinable public func chunked( by belongInSameGroup: @escaping (Element, Element) -> Bool - ) -> ChunkedBy { - ChunkedBy( + ) -> ChunkedByCollection { + ChunkedByCollection( base: elements, projection: { $0 }, belongInSameGroup: belongInSameGroup) @@ -219,13 +222,12 @@ extension LazyCollectionProtocol { /// /// - Complexity: O(*n*), because the start index is pre-computed. @inlinable - public func chunked( + public func chunked( on projection: @escaping (Element) -> Subject - ) -> ChunkedOn { - ChunkedOn( + ) -> ChunkedOnCollection { + ChunkedOnCollection( base: elements, - projection: projection, - belongInSameGroup: ==) + projection: projection) } } @@ -234,8 +236,8 @@ extension LazyCollectionProtocol { //===----------------------------------------------------------------------===// extension Collection { - /// Returns a collection of subsequences of this collection, chunked by - /// the given predicate. + /// Returns a collection of subsequences of this collection, chunked by the + /// given predicate. /// /// - Complexity: O(*n*), where *n* is the length of this collection. @inlinable @@ -257,7 +259,7 @@ extension Collection { } if start != endIndex { - result.append(self[start.. { - +/// * `c.lazy.chunks(ofCount: 3).map(f)` maps lazily and returns a +/// `LazyMapCollection` +public struct ChunksOfCountCollection { public typealias Element = Base.SubSequence @usableFromInline @@ -318,10 +321,10 @@ public struct ChunkedByCount { internal let chunkCount: Int @usableFromInline - internal var startUpperBound: Base.Index + internal var endOfFirstChunk: Base.Index - /// Creates a view instance that presents the elements of `base` - /// in `SubSequence` chunks of the given count. + /// Creates a view instance that presents the elements of `base` in + /// `SubSequence` chunks of the given count. /// /// - Complexity: O(*n*), because the start index is pre-computed. @inlinable @@ -329,16 +332,16 @@ public struct ChunkedByCount { self.base = _base self.chunkCount = _chunkCount - // Compute the start index upfront in order to make - // start index a O(1) lookup. - self.startUpperBound = _base.index( + // Compute the start index upfront in order to make start index a O(1) + // lookup. + self.endOfFirstChunk = _base.index( _base.startIndex, offsetBy: _chunkCount, limitedBy: _base.endIndex ) ?? _base.endIndex } } -extension ChunkedByCount: Collection { +extension ChunksOfCountCollection: Collection { public struct Index { @usableFromInline internal let baseRange: Range @@ -352,8 +355,9 @@ extension ChunkedByCount: Collection { /// - Complexity: O(1) @inlinable public var startIndex: Index { - Index(_baseRange: base.startIndex.. Element { - precondition(i < endIndex, "Index out of range") + precondition(i != endIndex, "Index out of range") return base[i.baseRange] } @inlinable public func index(after i: Index) -> Index { - precondition(i < endIndex, "Advancing past end index") + precondition(i != endIndex, "Advancing past end index") let baseIdx = base.index( i.baseRange.upperBound, offsetBy: chunkCount, limitedBy: base.endIndex @@ -377,30 +381,30 @@ extension ChunkedByCount: Collection { } } -extension ChunkedByCount.Index: Comparable { +extension ChunksOfCountCollection.Index: Comparable { @inlinable - public static func == (lhs: ChunkedByCount.Index, - rhs: ChunkedByCount.Index) -> Bool { + public static func == (lhs: ChunksOfCountCollection.Index, + rhs: ChunksOfCountCollection.Index) -> Bool { lhs.baseRange.lowerBound == rhs.baseRange.lowerBound } @inlinable - public static func < (lhs: ChunkedByCount.Index, - rhs: ChunkedByCount.Index) -> Bool { + public static func < (lhs: ChunksOfCountCollection.Index, + rhs: ChunksOfCountCollection.Index) -> Bool { lhs.baseRange.lowerBound < rhs.baseRange.lowerBound } } -extension ChunkedByCount: +extension ChunksOfCountCollection: BidirectionalCollection, RandomAccessCollection where Base: RandomAccessCollection { @inlinable public func index(before i: Index) -> Index { - precondition(i > startIndex, "Advancing past start index") + precondition(i != startIndex, "Advancing past start index") var offset = chunkCount if i.baseRange.lowerBound == base.endIndex { - let remainder = base.count%chunkCount + let remainder = base.count % chunkCount if remainder != 0 { offset = remainder } @@ -414,7 +418,7 @@ where Base: RandomAccessCollection { } } -extension ChunkedByCount { +extension ChunksOfCountCollection { @inlinable public func distance(from start: Index, to end: Index) -> Int { let distance = @@ -485,9 +489,9 @@ extension ChunkedByCount { let remainder = base.count%chunkCount // We have to take it into account when calculating offsets. if remainder != 0 { - // Distance "minus" one(at this point distance is negative) - // because we need to adjust for the last position that have - // a variadic(remainder) number of elements. + // Distance "minus" one(at this point distance is negative) because we + // need to adjust for the last position that have a variadic(remainder) + // number of elements. return ((distance + 1) * chunkCount) - remainder } } @@ -521,14 +525,13 @@ extension ChunkedByCount { if let limit = limit { if baseIdx == nil { - // If we past the bounds while advancing forward and the - // limit is the `endIndex`, since the computation on base - // don't take into account the remainder, we have to make - // sure that passing the bound was because of the distance - // not just because of a remainder. Special casing is less - // expensive than always use count(which could be O(n) for - // non-random access collection base) to compute the base - // distance taking remainder into account. + // If we past the bounds while advancing forward and the limit is the + // `endIndex`, since the computation on base don't take into account the + // remainder, we have to make sure that passing the bound was because of + // the distance not just because of a remainder. Special casing is less + // expensive than always use count(which could be O(n) for non-random + // access collection base) to compute the base distance taking remainder + // into account. if baseDistance > 0 && limit == endIndex { if self.distance(from: i, to: limit) < distance { return nil @@ -555,13 +558,13 @@ extension ChunkedByCount { } extension Collection { - /// Returns a `ChunkedCollection` view presenting the elements - /// in chunks with count of the given count parameter. + /// Returns a `ChunksOfCountCollection` view presenting the elements in + /// chunks with count of the given count parameter. /// - /// - Parameter size: The size of the chunks. If the count parameter - /// is evenly divided by the count of the base `Collection` all the - /// chunks will have the count equals to size. - /// Otherwise, the last chunk will contain the remaining elements. + /// - Parameter count: The size of the chunks. If the count parameter is + /// evenly divided by the count of the base `Collection` all the chunks will + /// have the count equals to size. Otherwise, the last chunk will contain + /// the remaining elements. /// /// let c = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] /// print(c.chunks(ofCount: 5).map(Array.init)) @@ -572,16 +575,13 @@ extension Collection { /// /// - Complexity: O(*n*), because the start index is pre-computed. @inlinable - public func chunks(ofCount count: Int) -> ChunkedByCount { + public func chunks(ofCount count: Int) -> ChunksOfCountCollection { precondition(count > 0, "Cannot chunk with count <= 0!") - return ChunkedByCount(_base: self, _chunkCount: count) + return ChunksOfCountCollection(_base: self, _chunkCount: count) } } -extension ChunkedByCount.Index: Hashable where Base.Index: Hashable {} +extension ChunksOfCountCollection.Index: Hashable where Base.Index: Hashable {} -// Lazy conditional conformance. -extension ChunkedByCount: LazySequenceProtocol +extension ChunksOfCountCollection: LazySequenceProtocol, LazyCollectionProtocol where Base: LazySequenceProtocol {} -extension ChunkedByCount: LazyCollectionProtocol - where Base: LazyCollectionProtocol {} diff --git a/Sources/Algorithms/Combinations.swift b/Sources/Algorithms/Combinations.swift index 7b4a421..2f26e9c 100644 --- a/Sources/Algorithms/Combinations.swift +++ b/Sources/Algorithms/Combinations.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// /// A collection wrapper that generates combinations of a base collection. -public struct Combinations { +public struct CombinationsSequence { /// The collection to iterate over for combinations. @usableFromInline internal let base: Base @@ -19,12 +19,15 @@ public struct Combinations { internal let baseCount: Int /// The range of accepted sizes of combinations. + /// /// - Note: This may be `nil` if the attempted range entirely exceeds the /// upper bounds of the size of the `base` collection. @usableFromInline internal let kRange: Range? - /// Initializes a `Combinations` for all combinations of `base` of size `k`. + /// Initializes a `CombinationsSequence` for all combinations of `base` of + /// size `k`. + /// /// - Parameters: /// - base: The collection to iterate over for combinations. /// - k: The expected size of each combination. @@ -33,8 +36,9 @@ public struct Combinations { self.init(base, kRange: k...k) } - /// Initializes a `Combinations` for all combinations of `base` of sizes - /// within a given range. + /// Initializes a `CombinationsSequence` for all combinations of `base` of + /// sizes within a given range. + /// /// - Parameters: /// - base: The collection to iterate over for combinations. /// - kRange: The range of accepted sizes of combinations. @@ -76,13 +80,14 @@ public struct Combinations { } } -extension Combinations: Sequence { - /// The iterator for a `Combinations` instance. +extension CombinationsSequence: Sequence { + /// The iterator for a `CombinationsSequence` instance. public struct Iterator: IteratorProtocol { @usableFromInline internal let base: Base /// The current range of accepted sizes of combinations. + /// /// - Note: The range is contracted until empty while iterating over /// combinations of different sizes. When the range is empty, iteration is /// finished. @@ -99,7 +104,7 @@ extension Combinations: Sequence { internal var indexes: [Base.Index] @inlinable - internal init(_ combinations: Combinations) { + internal init(_ combinations: CombinationsSequence) { self.base = combinations.base self.kRange = combinations.kRange ?? 0..<0 self.indexes = Array(combinations.base.indices.prefix(kRange.lowerBound)) @@ -175,12 +180,14 @@ extension Combinations: Sequence { } } + @inlinable public func makeIterator() -> Iterator { Iterator(self) } } -extension Combinations: LazySequenceProtocol where Base: LazySequenceProtocol {} +extension CombinationsSequence: LazySequenceProtocol + where Base: LazySequenceProtocol {} //===----------------------------------------------------------------------===// // combinations(ofCount:) @@ -243,16 +250,16 @@ extension Collection { /// limited range is empty, the resulting sequence has no elements. /// /// - Parameter kRange: The range of numbers of elements to include in each - /// combination. + /// combination. /// /// - Complexity: O(1) for random-access base collections. O(*n*) where *n* - /// is the number of elements in the base collection, since `Combinations` - /// accesses the `count` of the base collection. + /// is the number of elements in the base collection, since + /// `CombinationsSequence` accesses the `count` of the base collection. @inlinable public func combinations( ofCount kRange: R - ) -> Combinations where R.Bound == Int { - return Combinations(self, kRange: kRange) + ) -> CombinationsSequence where R.Bound == Int { + CombinationsSequence(self, kRange: kRange) } /// Returns a collection of combinations of this collection's elements, with @@ -282,11 +289,11 @@ extension Collection { /// - Parameter k: The number of elements to include in each combination. /// /// - Complexity: O(1) for random-access base collections. O(*n*) where *n* - /// is the number of elements in the base collection, since `Combinations` - /// accesses the `count` of the base collection. + /// is the number of elements in the base collection, since + /// `CombinationsSequence` accesses the `count` of the base collection. @inlinable - public func combinations(ofCount k: Int) -> Combinations { + public func combinations(ofCount k: Int) -> CombinationsSequence { precondition(k >= 0, "Can't have combinations with a negative number of elements.") - return Combinations(self, k: k) + return CombinationsSequence(self, k: k) } } diff --git a/Sources/Algorithms/Compacted.swift b/Sources/Algorithms/Compacted.swift index 788d34a..1e7ba48 100644 --- a/Sources/Algorithms/Compacted.swift +++ b/Sources/Algorithms/Compacted.swift @@ -9,7 +9,8 @@ // //===----------------------------------------------------------------------===// -/// A `Sequence` that iterates over every non-nil element from the original `Sequence`. +/// A `Sequence` that iterates over every non-nil element from the original +/// `Sequence`. public struct CompactedSequence: Sequence where Base.Element == Element? { @@ -42,14 +43,15 @@ public struct CompactedSequence: Sequence @inlinable public func makeIterator() -> Iterator { - return Iterator(base: base.makeIterator()) + 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 }`. + /// Returns a new `Sequence` that iterates over every non-nil element from the + /// original `Sequence`. + /// + /// Produces the same result as `c.compactMap { $0 }`. /// /// let c = [1, nil, 2, 3, nil] /// for num in c.compacted() { @@ -71,7 +73,8 @@ extension Sequence { } } -/// A `Collection` that iterates over every non-nil element from the original `Collection`. +/// A `Collection` that iterates over every non-nil element from the original +/// `Collection`. public struct CompactedCollection: Collection where Base.Element == Element? { @@ -143,9 +146,10 @@ 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 }`. + /// Returns a new `Collection` that iterates over every non-nil element from + /// the original `Collection`. + /// + /// Produces the same result as `c.compactMap { $0 }`. /// /// let c = [1, nil, 2, 3, nil] /// for num in c.compacted() { @@ -163,7 +167,8 @@ extension Collection { /// original `Collection`. @inlinable public func compacted() -> CompactedCollection - where Element == Unwrapped? { + where Element == Unwrapped? + { CompactedCollection(base: self) } } @@ -175,7 +180,5 @@ extension Collection { extension CompactedSequence: LazySequenceProtocol where Base: LazySequenceProtocol {} -extension CompactedCollection: LazySequenceProtocol +extension CompactedCollection: LazySequenceProtocol, LazyCollectionProtocol where Base: LazySequenceProtocol {} -extension CompactedCollection: LazyCollectionProtocol - where Base: LazyCollectionProtocol {} diff --git a/Sources/Algorithms/Cycle.swift b/Sources/Algorithms/Cycle.swift index fc6671d..23d1416 100644 --- a/Sources/Algorithms/Cycle.swift +++ b/Sources/Algorithms/Cycle.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// /// A collection wrapper that repeats the elements of a base collection. -public struct Cycle { +public struct CycledSequence { /// The collection to repeat. @usableFromInline internal let base: Base @@ -21,8 +21,8 @@ public struct Cycle { } } -extension Cycle: Sequence { - /// The iterator for a `Cycle` sequence. +extension CycledSequence: Sequence { + /// The iterator for a `CycledSequence` instance. public struct Iterator: IteratorProtocol { @usableFromInline internal let base: Base @@ -55,36 +55,33 @@ extension Cycle: Sequence { } } -extension Cycle: LazySequenceProtocol where Base: LazySequenceProtocol {} - +extension CycledSequence: LazySequenceProtocol + where Base: LazySequenceProtocol {} /// A collection wrapper that repeats the elements of a base collection for a /// finite number of times. -public struct FiniteCycle { - /// A Product2 instance for iterating the Base collection. +public struct CycledTimesCollection { + /// A `Product2Sequence` instance for iterating the base collection. @usableFromInline - internal let product: Product2, Base> + internal let product: Product2Sequence, Base> @inlinable internal init(base: Base, times: Int) { - self.product = Product2(0.., Base>.Index + internal let productIndex: Product2Sequence, Base>.Index @inlinable - internal init(_ productIndex: Product2, Base>.Index) { + internal init(_ productIndex: Product2Sequence, Base>.Index) { self.productIndex = productIndex } @@ -137,11 +134,11 @@ extension FiniteCycle: Collection { offsetBy distance: Int, limitedBy limit: Index ) -> Index? { - guard let productIndex = product.index(i.productIndex, - offsetBy: distance, - limitedBy: limit.productIndex) else { - return nil - } + guard let productIndex = product.index( + i.productIndex, + offsetBy: distance, + limitedBy: limit.productIndex) + else { return nil } return Index(productIndex) } @@ -151,7 +148,7 @@ extension FiniteCycle: Collection { } } -extension FiniteCycle: BidirectionalCollection +extension CycledTimesCollection: BidirectionalCollection where Base: BidirectionalCollection { @inlinable public func index(before i: Index) -> Index { @@ -160,9 +157,12 @@ extension FiniteCycle: BidirectionalCollection } } -extension FiniteCycle: RandomAccessCollection +extension CycledTimesCollection: RandomAccessCollection where Base: RandomAccessCollection {} +extension CycledTimesCollection: LazySequenceProtocol, LazyCollectionProtocol + where Base: LazySequenceProtocol {} + //===----------------------------------------------------------------------===// // cycled() //===----------------------------------------------------------------------===// @@ -194,8 +194,8 @@ extension Collection { /// /// - Complexity: O(1) @inlinable - public func cycled() -> Cycle { - Cycle(base: self) + public func cycled() -> CycledSequence { + CycledSequence(base: self) } /// Returns a sequence that repeats the elements of this collection the @@ -216,7 +216,7 @@ extension Collection { /// /// - Complexity: O(1) @inlinable - public func cycled(times: Int) -> FiniteCycle { - FiniteCycle(base: self, times: times) + public func cycled(times: Int) -> CycledTimesCollection { + CycledTimesCollection(base: self, times: times) } } diff --git a/Sources/Algorithms/FirstNonNil.swift b/Sources/Algorithms/FirstNonNil.swift index 0c15c83..f9719f3 100644 --- a/Sources/Algorithms/FirstNonNil.swift +++ b/Sources/Algorithms/FirstNonNil.swift @@ -13,7 +13,7 @@ // firstNonNil(_:) //===----------------------------------------------------------------------===// -public extension Sequence { +extension Sequence { /// Returns the first non-`nil` result obtained from applying the given /// transformation to the elements of the sequence. /// @@ -30,7 +30,8 @@ public 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. - func firstNonNil( + @inlinable + public func firstNonNil( _ transform: (Element) throws -> Result? ) rethrows -> Result? { for value in self { diff --git a/Sources/Algorithms/FlattenCollection.swift b/Sources/Algorithms/FlattenCollection.swift index d4b6f29..23b8a87 100644 --- a/Sources/Algorithms/FlattenCollection.swift +++ b/Sources/Algorithms/FlattenCollection.swift @@ -12,7 +12,9 @@ /// A collection consisting of all the elements contained in a collection of /// collections. @usableFromInline -internal struct FlattenCollection where Base.Element: Collection { +internal struct FlattenCollection + where Base.Element: Collection +{ @usableFromInline internal let base: Base @@ -97,7 +99,9 @@ extension FlattenCollection: Collection { guard let startInner = start.inner else { return 0 } guard start.outer != end.outer - else { return base[start.outer].distance(from: startInner, to: end.inner!) } + else { + return base[start.outer].distance(from: startInner, to: end.inner!) + } let firstPart = base[start.outer][startInner...].count let middlePart = base[start.outer.. { - /// The element type for an `Indexed` collection. - public typealias Element = (index: Base.Index, element: Base.Element) - +public struct IndexedCollection { /// The base collection. @usableFromInline internal let base: Base @@ -25,7 +22,10 @@ public struct Indexed { } } -extension Indexed: Collection { +extension IndexedCollection: Collection { + /// The element type for an `IndexedCollection` collection. + public typealias Element = (index: Base.Index, element: Base.Element) + @inlinable public var startIndex: Base.Index { base.startIndex @@ -52,7 +52,11 @@ extension Indexed: Collection { } @inlinable - public func index(_ i: Base.Index, offsetBy distance: Int, limitedBy limit: Base.Index) -> Base.Index? { + public func index( + _ i: Base.Index, + offsetBy distance: Int, + limitedBy limit: Base.Index + ) -> Base.Index? { base.index(i, offsetBy: distance, limitedBy: limit) } @@ -60,18 +64,27 @@ extension Indexed: Collection { public func distance(from start: Base.Index, to end: Base.Index) -> Int { base.distance(from: start, to: end) } + + @inlinable + public var indices: Base.Indices { + base.indices + } } -extension Indexed: BidirectionalCollection where Base: BidirectionalCollection { +extension IndexedCollection: BidirectionalCollection + where Base: BidirectionalCollection +{ @inlinable public func index(before i: Base.Index) -> Base.Index { base.index(before: i) } } -extension Indexed: RandomAccessCollection where Base: RandomAccessCollection {} -extension Indexed: LazySequenceProtocol where Base: LazySequenceProtocol {} -extension Indexed: LazyCollectionProtocol where Base: LazyCollectionProtocol {} +extension IndexedCollection: RandomAccessCollection + where Base: RandomAccessCollection {} + +extension IndexedCollection: LazySequenceProtocol, LazyCollectionProtocol + where Base: LazySequenceProtocol {} //===----------------------------------------------------------------------===// // indexed() @@ -94,7 +107,7 @@ extension Collection { /// /// Returns: A collection of paired indices and elements of this collection. @inlinable - public func indexed() -> Indexed { - Indexed(base: self) + public func indexed() -> IndexedCollection { + IndexedCollection(base: self) } } diff --git a/Sources/Algorithms/Intersperse.swift b/Sources/Algorithms/Intersperse.swift index 3fa804d..706c4ea 100644 --- a/Sources/Algorithms/Intersperse.swift +++ b/Sources/Algorithms/Intersperse.swift @@ -13,9 +13,9 @@ // Intersperse //===----------------------------------------------------------------------===// -/// A sequence that presents the elements of a base sequence of elements -/// with a separator between each of those elements. -public struct Intersperse { +/// A sequence that presents the elements of a base sequence of elements with a +/// separator between each of those elements. +public struct InterspersedSequence { @usableFromInline internal let base: Base @@ -29,9 +29,16 @@ public struct Intersperse { } } -extension Intersperse: Sequence { - /// The iterator for an `Intersperse` sequence. +extension InterspersedSequence: Sequence { + /// The iterator for an `InterspersedSequence` sequence. public struct Iterator: IteratorProtocol { + @usableFromInline + internal enum State { + case start + case element(Base.Element) + case separator + } + @usableFromInline internal var iterator: Base.Iterator @@ -46,13 +53,6 @@ extension Intersperse: Sequence { self.iterator = iterator self.separator = separator } - - @usableFromInline - enum State { - case start - case element(Base.Element) - case separator - } @inlinable public mutating func next() -> Base.Element? { @@ -76,13 +76,13 @@ extension Intersperse: Sequence { } @inlinable - public func makeIterator() -> Intersperse.Iterator { + public func makeIterator() -> InterspersedSequence.Iterator { Iterator(iterator: base.makeIterator(), separator: separator) } } -extension Intersperse: Collection where Base: Collection { - /// A position in an `Intersperse` collection. +extension InterspersedSequence: Collection where Base: Collection { + /// A position in an `InterspersedSequence` instance. public struct Index: Comparable { @usableFromInline internal enum Representation: Equatable { @@ -256,7 +256,7 @@ extension Intersperse: Collection where Base: Collection { } } -extension Intersperse: BidirectionalCollection +extension InterspersedSequence: BidirectionalCollection where Base: BidirectionalCollection { @inlinable @@ -271,14 +271,14 @@ extension Intersperse: BidirectionalCollection } } -extension Intersperse: RandomAccessCollection +extension InterspersedSequence: RandomAccessCollection where Base: RandomAccessCollection {} -extension Intersperse: LazySequenceProtocol +extension InterspersedSequence: LazySequenceProtocol where Base: LazySequenceProtocol {} -extension Intersperse: LazyCollectionProtocol - where Base: LazyCollectionProtocol {} +extension InterspersedSequence: LazyCollectionProtocol + where Base: LazySequenceProtocol & Collection {} //===----------------------------------------------------------------------===// // InterspersedMap @@ -289,7 +289,7 @@ extension Intersperse: LazyCollectionProtocol /// elements, with a separator that separates each pair of adjacent transformed /// values. @usableFromInline -internal struct InterspersedMap { +internal struct InterspersedMapSequence { @usableFromInline internal let base: Base @@ -300,9 +300,16 @@ internal struct InterspersedMap { internal let separator: (Base.Element, Base.Element) -> Result } -extension InterspersedMap: Sequence { +extension InterspersedMapSequence: Sequence { @usableFromInline internal struct Iterator: IteratorProtocol { + @usableFromInline + internal enum State { + case start + case element(Base.Element) + case separator(previous: Base.Element) + } + @usableFromInline internal var base: Base.Iterator @@ -325,13 +332,6 @@ extension InterspersedMap: Sequence { 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? { @@ -360,11 +360,11 @@ extension InterspersedMap: Sequence { } } -extension InterspersedMap: Collection where Base: Collection { +extension InterspersedMapSequence: Collection where Base: Collection { @usableFromInline internal struct Index: Comparable { @usableFromInline - internal enum Representation: Equatable { + internal enum Representation { case element(Base.Index) case separator(previous: Base.Index, next: Base.Index) } @@ -561,7 +561,7 @@ extension InterspersedMap: Collection where Base: Collection { } } -extension InterspersedMap: BidirectionalCollection +extension InterspersedMapSequence: BidirectionalCollection where Base: BidirectionalCollection { @inlinable @@ -577,20 +577,31 @@ extension InterspersedMap: BidirectionalCollection } } -extension InterspersedMap.Index.Representation: Hashable - where Base.Index: Hashable {} +extension InterspersedMapSequence.Index: Hashable + where Base.Index: Hashable +{ + @inlinable + internal func hash(into hasher: inout Hasher) { + switch representation { + case .element(let base): + hasher.combine(false) + hasher.combine(base) + case .separator(_, let next): + hasher.combine(true) + hasher.combine(next) + } + } +} -extension InterspersedMap: LazySequenceProtocol - where Base: LazySequenceProtocol {} -extension InterspersedMap: LazyCollectionProtocol - where Base: LazyCollectionProtocol {} +extension InterspersedMapSequence: LazySequenceProtocol {} +extension InterspersedMapSequence: LazyCollectionProtocol + where Base: Collection {} //===----------------------------------------------------------------------===// // interspersed(with:) //===----------------------------------------------------------------------===// extension Sequence { - /// Returns a sequence containing elements of this sequence with the given /// separator inserted in between each element. /// @@ -620,13 +631,15 @@ extension Sequence { /// /// - Complexity: O(1) @inlinable - public func interspersed(with separator: Element) -> Intersperse { - Intersperse(base: self, separator: separator) + public func interspersed( + with separator: Element + ) -> InterspersedSequence { + InterspersedSequence(base: self, separator: separator) } } //===----------------------------------------------------------------------===// -// lazy.interspersed(_:with:) +// lazy.interspersedMap(_:with:) //===----------------------------------------------------------------------===// extension LazySequenceProtocol { @@ -647,7 +660,10 @@ extension LazySequenceProtocol { internal func interspersedMap( _ transform: @escaping (Element) -> Result, with separator: @escaping (Element, Element) -> Result - ) -> InterspersedMap { - InterspersedMap(base: self, transform: transform, separator: separator) + ) -> InterspersedMapSequence { + InterspersedMapSequence( + base: elements, + transform: transform, + separator: separator) } } diff --git a/Sources/Algorithms/Joined.swift b/Sources/Algorithms/Joined.swift index d630a2d..13f2f69 100644 --- a/Sources/Algorithms/Joined.swift +++ b/Sources/Algorithms/Joined.swift @@ -19,8 +19,8 @@ public struct JoinedBySequence where Base.Element: Sequence, Base.Element.Element == Separator.Element { @usableFromInline - internal typealias Inner = FlattenSequence< - Intersperse>>> + internal typealias Inner = FlattenSequence>>> @usableFromInline internal let inner: Inner @@ -70,8 +70,8 @@ public struct JoinedByClosureSequence where Base.Element: Sequence, Base.Element.Element == Separator.Element { @usableFromInline - internal typealias Inner = FlattenSequence< - InterspersedMap, EitherSequence>> + internal typealias Inner = FlattenSequence>> @usableFromInline internal let inner: Inner @@ -111,8 +111,7 @@ extension JoinedByClosureSequence: Sequence { } } -extension JoinedByClosureSequence: LazySequenceProtocol - where Base: LazySequenceProtocol {} +extension JoinedByClosureSequence: LazySequenceProtocol {} //===----------------------------------------------------------------------===// // JoinedByCollection @@ -124,8 +123,8 @@ public struct JoinedByCollection where Base.Element: Collection, Base.Element.Element == Separator.Element { @usableFromInline - internal typealias Inner = FlattenCollection< - Intersperse>>> + internal typealias Inner = FlattenCollection>>> @usableFromInline internal let inner: Inner @@ -212,10 +211,8 @@ extension JoinedByCollection: BidirectionalCollection } } -extension JoinedByCollection: LazySequenceProtocol +extension JoinedByCollection: LazySequenceProtocol, LazyCollectionProtocol where Base: LazySequenceProtocol {} -extension JoinedByCollection: LazyCollectionProtocol - where Base: LazyCollectionProtocol {} //===----------------------------------------------------------------------===// // JoinedByClosureCollection @@ -228,8 +225,8 @@ public struct JoinedByClosureCollection where Base.Element: Collection, Base.Element.Element == Separator.Element { @usableFromInline - internal typealias Inner = FlattenCollection< - InterspersedMap, EitherSequence>> + internal typealias Inner = FlattenCollection>> @usableFromInline internal let inner: Inner @@ -320,10 +317,7 @@ extension JoinedByClosureCollection: BidirectionalCollection } } -extension JoinedByClosureCollection: LazySequenceProtocol - where Base: LazySequenceProtocol {} -extension JoinedByClosureCollection: LazyCollectionProtocol - where Base: LazyCollectionProtocol {} +extension JoinedByClosureCollection: LazyCollectionProtocol {} //===----------------------------------------------------------------------===// // Sequence.joined(by:) @@ -420,7 +414,7 @@ extension LazySequenceProtocol where Element: Sequence { @inlinable public func joined( by separator: @escaping (Element, Element) -> Element.Element - ) -> JoinedByClosureSequence> { + ) -> JoinedByClosureSequence> { joined(by: { CollectionOfOne(separator($0, $1)) }) } @@ -429,8 +423,8 @@ extension LazySequenceProtocol where Element: Sequence { @inlinable public func joined( by separator: @escaping (Element, Element) -> Separator - ) -> JoinedByClosureSequence { - JoinedByClosureSequence(base: self, separator: separator) + ) -> JoinedByClosureSequence { + JoinedByClosureSequence(base: elements, separator: separator) } } @@ -469,17 +463,17 @@ extension Collection where Element: Collection { } //===----------------------------------------------------------------------===// -// LazyCollectionProtocol.joined(by:) +// LazySequenceProtocol.joined(by:) where Self: Collection //===----------------------------------------------------------------------===// -extension LazyCollectionProtocol where Element: Collection { +extension LazySequenceProtocol where Elements: Collection, Element: Collection { /// Returns the concatenation of the elements in this collection of /// collections, inserting the separator produced by the closure between each /// sequence. @inlinable public func joined( by separator: @escaping (Element, Element) -> Element.Element - ) -> JoinedByClosureCollection> { + ) -> JoinedByClosureCollection> { joined(by: { CollectionOfOne(separator($0, $1)) }) } @@ -489,7 +483,7 @@ extension LazyCollectionProtocol where Element: Collection { @inlinable public func joined( by separator: @escaping (Element, Element) -> Separator - ) -> JoinedByClosureCollection { - JoinedByClosureCollection(base: self, separator: separator) + ) -> JoinedByClosureCollection { + JoinedByClosureCollection(base: elements, separator: separator) } } diff --git a/Sources/Algorithms/MinMax.swift b/Sources/Algorithms/MinMax.swift index 045dd35..1ca66cb 100644 --- a/Sources/Algorithms/MinMax.swift +++ b/Sources/Algorithms/MinMax.swift @@ -190,7 +190,7 @@ extension Sequence where Element: Comparable { /// sequence and *k* is `count`. @inlinable public func min(count: Int) -> [Element] { - return min(count: count, sortedBy: <) + min(count: count, sortedBy: <) } /// Returns the largest elements of this sequence. @@ -216,7 +216,7 @@ extension Sequence where Element: Comparable { /// sequence and *k* is `count`. @inlinable public func max(count: Int) -> [Element] { - return max(count: count, sortedBy: <) + max(count: count, sortedBy: <) } } @@ -354,7 +354,7 @@ extension Collection where Element: Comparable { /// collection and *k* is `count`. @inlinable public func min(count: Int) -> [Element] { - return min(count: count, sortedBy: <) + min(count: count, sortedBy: <) } /// Returns the largest elements of this collection. @@ -380,7 +380,7 @@ extension Collection where Element: Comparable { /// collection and *k* is `count`. @inlinable public func max(count: Int) -> [Element] { - return max(count: count, sortedBy: <) + max(count: count, sortedBy: <) } } @@ -392,9 +392,8 @@ 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: + /// 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 @@ -405,9 +404,9 @@ extension Sequence { /// 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. + /// 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}) { @@ -419,9 +418,9 @@ extension Sequence { /// /// - 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`. + /// - 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 @@ -429,6 +428,7 @@ extension Sequence { /// method returns `nil`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. + @inlinable public func minAndMax( by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows -> (min: Element, max: Element)? { @@ -479,6 +479,6 @@ extension Sequence where Element: Comparable { /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func minAndMax() -> (min: Element, max: Element)? { - return minAndMax(by: <) + minAndMax(by: <) } } diff --git a/Sources/Algorithms/Partition.swift b/Sources/Algorithms/Partition.swift index 66a0b01..48f1b1e 100644 --- a/Sources/Algorithms/Partition.swift +++ b/Sources/Algorithms/Partition.swift @@ -14,9 +14,9 @@ //===----------------------------------------------------------------------===// extension MutableCollection { - /// Moves all elements satisfying `belongsInSecondPartition` into a suffix - /// of the collection, preserving their relative order, and returns the - /// start of the resulting suffix. + /// Moves all elements satisfying `belongsInSecondPartition` into a suffix of + /// the collection, preserving their relative order, and returns the start of + /// the resulting suffix. /// /// - Complexity: O(*n* log *n*), where *n* is the number of elements. /// - Precondition: @@ -25,7 +25,7 @@ extension MutableCollection { internal mutating func stablePartition( count n: Int, subrange: Range, - by belongsInSecondPartition: (Element) throws-> Bool + by belongsInSecondPartition: (Element) throws -> Bool ) rethrows -> Index { if n == 0 { return subrange.lowerBound } if n == 1 { @@ -138,22 +138,22 @@ extension MutableCollection where Self: BidirectionalCollection { // * predicate(self[i]) == true, for i in hi ..< endIndex Loop: while true { - FindLo: repeat { + FindLo: do { while lo < hi { if try belongsInSecondPartition(self[lo]) { break FindLo } formIndex(after: &lo) } break Loop - } while false + } - FindHi: repeat { + FindHi: do { formIndex(before: &hi) while lo < hi { if try !belongsInSecondPartition(self[hi]) { break FindHi } formIndex(before: &hi) } break Loop - } while false + } swapAt(lo, hi) formIndex(after: &lo) @@ -173,8 +173,8 @@ extension Collection { /// /// The collection must already be partitioned according to the predicate. /// That is, there should be an index `i` where for every element in - /// `collection[.. { +public struct PermutationsSequence { /// The base collection to iterate over for permutations. @usableFromInline internal let base: Base @@ -85,12 +85,15 @@ public struct Permutations { internal let baseCount: Int /// The range of accepted sizes of permutations. + /// /// - Note: This may be empty if the attempted range entirely exceeds the /// bounds of the size of the `base` collection. @usableFromInline internal let kRange: Range - /// Initializes a `Permutations` for all permutations of `base` of size `k`. + /// Initializes a `PermutationsSequence` for all permutations of `base` of + /// size `k`. + /// /// - Parameters: /// - base: The collection to iterate over for permutations /// - k: The expected size of each permutation, or `nil` (default) to @@ -106,8 +109,9 @@ public struct Permutations { self.init(base, kRange: kRange) } - /// Initializes a `Permutations` for all combinations of `base` of sizes - /// within a given range. + /// Initializes a `PermutationsSequence` for all combinations of `base` of + /// sizes within a given range. + /// /// - Parameters: /// - base: The collection to iterate over for permutations. /// - kRange: The range of accepted sizes of permutations, or `nil` to @@ -128,14 +132,14 @@ public struct Permutations { /// The total number of permutations. @inlinable public var count: Int { - return kRange.map { + kRange.map { stride(from: baseCount, to: baseCount - $0, by: -1).reduce(1, *) }.reduce(0, +) } } -extension Permutations: Sequence { - /// The iterator for a `Permutations` instance. +extension PermutationsSequence: Sequence { + /// The iterator for a `PermutationsSequence` instance. public struct Iterator: IteratorProtocol { @usableFromInline internal let base: Base @@ -160,7 +164,7 @@ extension Permutations: Sequence { internal var indexes: [Base.Index] @inlinable - internal init(_ permutations: Permutations) { + internal init(_ permutations: PermutationsSequence) { self.base = permutations.base self.baseCount = permutations.baseCount self.kRange = permutations.kRange @@ -259,7 +263,8 @@ extension Permutations: Sequence { } } -extension Permutations: LazySequenceProtocol where Base: LazySequenceProtocol {} +extension PermutationsSequence: LazySequenceProtocol + where Base: LazySequenceProtocol {} //===----------------------------------------------------------------------===// // permutations(ofCount:) @@ -320,13 +325,13 @@ extension Collection { /// results in an empty sequence. /// /// - Complexity: O(1) for random-access base collections. O(*n*) where *n* - /// is the number of elements in the base collection, since `Permutations` - /// accesses the `count` of the base collection. + /// is the number of elements in the base collection, since + /// `PermutationsSequence` accesses the `count` of the base collection. @inlinable public func permutations( ofCount kRange: R - ) -> Permutations where R.Bound == Int { - return Permutations(self, kRange: kRange) + ) -> PermutationsSequence where R.Bound == Int { + PermutationsSequence(self, kRange: kRange) } /// Returns a collection of the permutations of this collection of the @@ -376,14 +381,14 @@ extension Collection { /// this collection, the resulting sequence is empty. /// /// - Complexity: O(1) for random-access base collections. O(*n*) where *n* - /// is the number of elements in the base collection, since `Permutations` - /// accesses the `count` of the base collection. + /// is the number of elements in the base collection, since + /// `PermutationsSequence` accesses the `count` of the base collection. @inlinable - public func permutations(ofCount k: Int? = nil) -> Permutations { + public func permutations(ofCount k: Int? = nil) -> PermutationsSequence { precondition( k ?? 0 >= 0, "Can't have permutations with a negative number of elements.") - return Permutations(self, k: k) + return PermutationsSequence(self, k: k) } } @@ -394,9 +399,9 @@ extension Collection { /// A sequence of the unique permutations of the elements of a sequence or /// collection. /// -/// To create a `UniquePermutations` instance, call one of the +/// To create a `UniquePermutationsSequence` instance, call one of the /// `uniquePermutations` methods on your collection. -public struct UniquePermutations { +public struct UniquePermutationsSequence { /// The base collection to iterate over for permutations. @usableFromInline internal let base: Base @@ -408,7 +413,7 @@ public struct UniquePermutations { internal let kRange: Range } -extension UniquePermutations where Base.Element: Hashable { +extension UniquePermutationsSequence where Base.Element: Hashable { @inlinable internal static func _indexes(_ base: Base) -> [Base.Index] { let firstIndexesAndCountsByElement = Dictionary( @@ -440,8 +445,8 @@ extension UniquePermutations where Base.Element: Hashable { } } -extension UniquePermutations: Sequence { - /// The iterator for a `UniquePermutations` instance. +extension UniquePermutationsSequence: Sequence { + /// The iterator for a `UniquePermutationsSequence` instance. public struct Iterator: IteratorProtocol { @usableFromInline internal let base: Base @@ -496,7 +501,8 @@ extension UniquePermutations: Sequence { } } -extension UniquePermutations: LazySequenceProtocol where Base: LazySequenceProtocol {} +extension UniquePermutationsSequence: LazySequenceProtocol + where Base: LazySequenceProtocol {} extension Collection where Element: Hashable { /// Returns a sequence of the unique permutations of this sequence of the @@ -537,11 +543,14 @@ extension Collection where Element: Hashable { /// /// - Complexity: O(*n*), where *n* is the number of elements in this /// collection. - public func uniquePermutations(ofCount k: Int? = nil) -> UniquePermutations { + @inlinable + public func uniquePermutations(ofCount k: Int? = nil) + -> UniquePermutationsSequence + { if let k = k { - return UniquePermutations(self, k ..< (k + 1)) + return UniquePermutationsSequence(self, k ..< (k + 1)) } else { - return UniquePermutations(self) + return UniquePermutationsSequence(self) } } @@ -574,9 +583,10 @@ extension Collection where Element: Hashable { /// /// - Complexity: O(*n*), where *n* is the number of elements in this /// collection. - public func uniquePermutations(ofCount kRange: R) -> UniquePermutations - where R.Bound == Int - { - UniquePermutations(self, kRange) + @inlinable + public func uniquePermutations( + ofCount kRange: R + ) -> UniquePermutationsSequence where R.Bound == Int { + UniquePermutationsSequence(self, kRange) } } diff --git a/Sources/Algorithms/Product.swift b/Sources/Algorithms/Product.swift index dd6b8b0..d5611e9 100644 --- a/Sources/Algorithms/Product.swift +++ b/Sources/Algorithms/Product.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// /// A sequence that represents the product of two sequences' elements. -public struct Product2 { +public struct Product2Sequence { /// The outer sequence in the product. @usableFromInline internal let base1: Base1 @@ -26,10 +26,10 @@ public struct Product2 { } } -extension Product2: Sequence { +extension Product2Sequence: Sequence { public typealias Element = (Base1.Element, Base2.Element) - /// The iterator for a `Product2` sequence. + /// The iterator for a `Product2Sequence` sequence. public struct Iterator: IteratorProtocol { @usableFromInline internal var i1: Base1.Iterator @@ -41,7 +41,7 @@ extension Product2: Sequence { internal let base2: Base2 @inlinable - internal init(_ c: Product2) { + internal init(_ c: Product2Sequence) { self.base2 = c.base2 self.i1 = c.base1.makeIterator() self.i2 = c.base2.makeIterator() @@ -83,13 +83,14 @@ extension Product2: Sequence { } } + @inlinable public func makeIterator() -> Iterator { - return Iterator(self) + Iterator(self) } } -extension Product2: Collection where Base1: Collection { - /// The index type for a `Product2` collection. +extension Product2Sequence: Collection where Base1: Collection { + /// The index type for a `Product2Sequence` collection. public struct Index: Comparable { @usableFromInline internal var i1: Base1.Index @@ -419,7 +420,7 @@ extension Product2: Collection where Base1: Collection { } } -extension Product2: BidirectionalCollection +extension Product2Sequence: BidirectionalCollection where Base1: BidirectionalCollection, Base2: BidirectionalCollection { @inlinable @@ -436,10 +437,11 @@ extension Product2: BidirectionalCollection } } -extension Product2: RandomAccessCollection +extension Product2Sequence: RandomAccessCollection where Base1: RandomAccessCollection, Base2: RandomAccessCollection {} -extension Product2.Index: Hashable where Base1.Index: Hashable, Base2.Index: Hashable {} +extension Product2Sequence.Index: Hashable + where Base1.Index: Hashable, Base2.Index: Hashable {} //===----------------------------------------------------------------------===// // product(_:_:) @@ -481,6 +483,6 @@ extension Product2.Index: Hashable where Base1.Index: Hashable, Base2.Index: Has @inlinable public func product( _ s1: Base1, _ s2: Base2 -) -> Product2 { - return Product2(s1, s2) +) -> Product2Sequence { + Product2Sequence(s1, s2) } diff --git a/Sources/Algorithms/RandomSample.swift b/Sources/Algorithms/RandomSample.swift index 6542476..933269d 100644 --- a/Sources/Algorithms/RandomSample.swift +++ b/Sources/Algorithms/RandomSample.swift @@ -62,8 +62,7 @@ extension Collection { /// This method is equivalent to calling `randomStableSample(k:using:)`, /// passing in the system's default random generator. /// - /// - Parameters: - /// - k: The number of elements to randomly select. + /// - Parameter k: The number of elements to randomly select. /// - Returns: An array of `k` random elements. If `k` is greater than this /// collection's count, then this method returns the full collection. /// @@ -123,12 +122,12 @@ extension Collection { // Fill the reservoir with the first `k` elements. var i = startIndex - while i < endIndex, result.count < k { + while i != endIndex, result.count < k { result.append(self[i]) formIndex(after: &i) } - while i < endIndex { + while i != endIndex { // Calculate the next value of w. w *= nextW(k: k, using: &rng) @@ -136,7 +135,7 @@ extension Collection { let offset = nextOffset(w: w, using: &rng) i = index(i, offsetBy: offset, limitedBy: endIndex) ?? endIndex - if i < endIndex { + if i != endIndex { // Swap selected element with a randomly chosen one in the reservoir. let j = Int.random(in: 0..( _ initial: Result, _ transform: @escaping (Result, Element) -> Result - ) -> ExclusiveReductions { - return reductions(into: initial) { result, element in + ) -> ExclusiveReductionsSequence { + reductions(into: initial) { result, element in result = transform(result, element) } } @@ -60,7 +59,7 @@ extension LazySequenceProtocol { /// - Parameters: /// - initial: The value to use as the initial value. /// - transform: A closure that combines the previously reduced result and - /// the next element in the receiving sequence. + /// the next element in the receiving sequence. /// - Returns: A sequence of the initial value followed by the reduced /// elements. /// @@ -69,13 +68,15 @@ extension LazySequenceProtocol { public func reductions( into initial: Result, _ transform: @escaping (inout Result, Element) -> Void - ) -> ExclusiveReductions { - ExclusiveReductions(base: self, initial: initial, transform: transform) + ) -> ExclusiveReductionsSequence { + ExclusiveReductionsSequence( + base: elements, + initial: initial, + transform: transform) } } extension Sequence { - /// Returns an array containing the accumulated results of combining the /// elements of the sequence using the given closure. /// @@ -106,7 +107,7 @@ extension Sequence { /// - Parameters: /// - initial: The value to use as the initial value. /// - transform: A closure that combines the previously reduced result and - /// the next element in the receiving sequence. + /// the next element in the receiving sequence. /// - Returns: An array of the initial value followed by the reduced elements. /// /// - Complexity: O(_n_), where _n_ is the length of the sequence. @@ -115,7 +116,7 @@ extension Sequence { _ initial: Result, _ transform: (Result, Element) throws -> Result ) rethrows -> [Result] { - return try reductions(into: initial) { result, element in + try reductions(into: initial) { result, element in result = try transform(result, element) } } @@ -150,7 +151,7 @@ extension Sequence { /// - Parameters: /// - initial: The value to use as the initial value. /// - transform: A closure that combines the previously reduced result and - /// the next element in the receiving sequence. + /// the next element in the receiving sequence. /// - Returns: An array of the initial value followed by the reduced elements. /// /// - Complexity: O(_n_), where _n_ is the length of the sequence. @@ -176,7 +177,7 @@ extension Sequence { /// A sequence of applying a transform to the element of a sequence and the /// previously transformed result. -public struct ExclusiveReductions { +public struct ExclusiveReductionsSequence { @usableFromInline internal let base: Base @@ -198,7 +199,7 @@ public struct ExclusiveReductions { } } -extension ExclusiveReductions: Sequence { +extension ExclusiveReductionsSequence: Sequence { public struct Iterator: IteratorProtocol { @usableFromInline internal var iterator: Base.Iterator @@ -234,58 +235,82 @@ extension ExclusiveReductions: Sequence { @inlinable public func makeIterator() -> Iterator { - Iterator(iterator: base.makeIterator(), - current: initial, - transform: transform) + Iterator( + iterator: base.makeIterator(), + current: initial, + transform: transform) } } -extension ExclusiveReductions: Collection where Base: Collection { +extension ExclusiveReductionsSequence: Collection where Base: Collection { public struct Index: Comparable { @usableFromInline - internal let representation: ReductionsIndexRepresentation + internal enum Representation { + case base(Base.Index, Result) + case end + } + + @usableFromInline + internal let representation: Representation @inlinable - internal init( - _ representation: ReductionsIndexRepresentation - ) { + internal init(_ representation: Representation) { self.representation = representation } - + + @inlinable + public static func == (lhs: Self, rhs: Self) -> Bool { + switch (lhs.representation, rhs.representation) { + case (.base(let lhs, _), .base(let rhs, _)): + return lhs == rhs + case (.end, .end): + return true + case (.base, .end), (.end, .base): + return false + } + } + @inlinable public static func < (lhs: Self, rhs: Self) -> Bool { - lhs.representation < rhs.representation + switch (lhs.representation, rhs.representation) { + case (.end, _): + return false + case (_, .end): + return true + case (.base(let lhs, _), .base(let rhs, _)): + return lhs < rhs + } } } @inlinable - public var startIndex: Index { Index(.start) } + public var startIndex: Index { + Index(.base(base.startIndex, initial)) + } @inlinable - public var endIndex: Index { Index(.end) } + public var endIndex: Index { + Index(.end) + } @inlinable public subscript(position: Index) -> Result { switch position.representation { - case .start: return initial - case .base(_, let result): return result - case .end: fatalError("Cannot get element of end index.") + case .base(_, let result): + return result + case .end: + fatalError("Cannot get element of end index.") } } @inlinable - public func index(after i: Index) -> Index { - func index(base index: Base.Index, previous: Result) -> Index { - guard index != base.endIndex else { return endIndex } - var previous = previous - transform(&previous, base[index]) - return Index(.base(index: index, result: previous)) - } - switch i.representation { - case .start: - return index(base: base.startIndex, previous: initial) - case let .base(i, result): - return index(base: base.index(after: i), previous: result) + public func index(after index: Index) -> Index { + switch index.representation { + case .base(base.endIndex, _): + return Index(.end) + case .base(let index, var result): + transform(&result, base[index]) + return Index(.base(base.index(after: index), result)) case .end: fatalError("Cannot get index after end index.") } @@ -294,38 +319,40 @@ extension ExclusiveReductions: Collection where Base: Collection { @inlinable public func distance(from start: Index, to end: Index) -> Int { switch (start.representation, end.representation) { - case (.start, .start): - return 0 - case let (.start, .base(index, _)): - return base.distance(from: base.startIndex, to: index) + 1 - case (.start, .end): - return base.distance(from: base.startIndex, to: base.endIndex) + 1 - case let (.base(index, _), .start): - return base.distance(from: index, to: base.startIndex) - 1 case let (.base(start, _), .base(end, _)): return base.distance(from: start, to: end) case let (.base(index, _), .end): - return base.distance(from: index, to: base.endIndex) - case (.end, .start): - return base.distance(from: base.endIndex, to: base.startIndex) - 1 + return base.distance(from: index, to: base.endIndex) + 1 case let (.end, .base(index, _)): - return base.distance(from: base.endIndex, to: index) + return base.distance(from: base.endIndex, to: index) - 1 case (.end, .end): return 0 } } } -extension ExclusiveReductions: LazySequenceProtocol - where Base: LazySequenceProtocol {} +extension ExclusiveReductionsSequence: LazySequenceProtocol {} -extension ExclusiveReductions: LazyCollectionProtocol - where Base: LazyCollectionProtocol {} +extension ExclusiveReductionsSequence: LazyCollectionProtocol + where Base: Collection {} + +extension ExclusiveReductionsSequence.Index: Hashable + where Base.Index: Hashable +{ + @inlinable + public func hash(into hasher: inout Hasher) { + switch representation { + case .base(let base, _): + hasher.combine(base) + case .end: + break + } + } +} // MARK: - Inclusive Reductions extension LazySequenceProtocol { - /// Returns a sequence containing the accumulated results of combining the /// elements of the sequence using the given closure. /// @@ -339,22 +366,20 @@ extension LazySequenceProtocol { /// // prints [1, 3, 6, 10] /// ``` /// - /// - Parameters: - /// - transform: A closure that combines the previously reduced result and - /// the next element in the receiving sequence. + /// - Parameter transform: A closure that combines the previously reduced + /// result and the next element in the receiving sequence. /// - Returns: A sequence of the reduced elements. /// /// - Complexity: O(1) @inlinable public func reductions( _ transform: @escaping (Element, Element) -> Element - ) -> InclusiveReductions { - InclusiveReductions(base: self, transform: transform) + ) -> InclusiveReductionsSequence { + InclusiveReductionsSequence(base: elements, transform: transform) } } extension Sequence { - /// Returns an array containing the accumulated results of combining the /// elements of the sequence using the given closure. /// @@ -384,9 +409,8 @@ extension Sequence { /// If the sequence has one element, `transform` is never executed and /// an array containing only that first element is returned. /// - /// - Parameters: - /// - transform: A closure that combines the previously reduced result and - /// the next element in the receiving sequence. + /// - Parameter transform: A closure that combines the previously reduced + /// result and the next element in the receiving sequence. /// - Returns: An array of the reduced elements. /// /// - Complexity: O(_n_), where _n_ is the length of the sequence. @@ -400,7 +424,7 @@ extension Sequence { } } -public struct InclusiveReductions { +public struct InclusiveReductionsSequence { @usableFromInline internal let base: Base @@ -417,7 +441,7 @@ public struct InclusiveReductions { } } -extension InclusiveReductions: Sequence { +extension InclusiveReductionsSequence: Sequence { public struct Iterator: IteratorProtocol { @usableFromInline internal var iterator: Base.Iterator @@ -431,11 +455,9 @@ extension InclusiveReductions: Sequence { @inlinable internal init( iterator: Base.Iterator, - element: Base.Element? = nil, transform: @escaping (Base.Element, Base.Element) -> Base.Element ) { self.iterator = iterator - self.element = element self.transform = transform } @@ -453,139 +475,97 @@ extension InclusiveReductions: Sequence { @inlinable public func makeIterator() -> Iterator { - Iterator(iterator: base.makeIterator(), - transform: transform) + Iterator(iterator: base.makeIterator(), transform: transform) } } -extension InclusiveReductions: Collection where Base: Collection { +extension InclusiveReductionsSequence: Collection where Base: Collection { public struct Index: Comparable { @usableFromInline - internal let representation: ReductionsIndexRepresentation + internal let base: Base.Index + + @usableFromInline + internal let result: Element? @inlinable - internal init( - _ representation: ReductionsIndexRepresentation - ) { - self.representation = representation + internal init(base: Base.Index, result: Element?) { + self.base = base + self.result = result } @inlinable public static func < (lhs: Self, rhs: Self) -> Bool { - lhs.representation < rhs.representation + lhs.base < rhs.base + } + + @inlinable + public static func == (lhs: Self, rhs: Self) -> Bool { + lhs.base == rhs.base } } @inlinable public var startIndex: Index { - guard base.startIndex != base.endIndex else { return endIndex } - return Index(.start) + Index(base: base.startIndex, result: base.first) } @inlinable - public var endIndex: Index { Index(.end) } - - @inlinable - public subscript(position: Index) -> Base.Element { - switch position.representation { - case .start: return base[base.startIndex] - case .base(_, let result): return result - case .end: fatalError("Cannot get element of end index.") - } + public var endIndex: Index { + Index(base: base.endIndex, result: nil) } @inlinable - public func index(after i: Index) -> Index { - func index(after i: Base.Index, previous: Base.Element) -> Index { - let index = base.index(after: i) - guard index != base.endIndex else { return endIndex } - return Index(.base(index: index, result: transform(previous, base[index]))) + public subscript(index: Index) -> Base.Element { + guard let result = index.result else { + fatalError("Can't subscript using endIndex") } - switch i.representation { - case .start: - return index(after: base.startIndex, previous: base[base.startIndex]) - case let .base(i, element): - return index(after: i, previous: element) - case .end: - fatalError("Cannot get index after end index.") + + return result + } + + @inlinable + public func index(after index: Index) -> Index { + guard let result = index.result else { + fatalError("Can't advance past endIndex") } + + let index = base.index(after: index.base) + let nextResult = index == base.endIndex + ? nil + : transform(result, base[index]) + + return Index(base: index, result: nextResult) } @inlinable public func distance(from start: Index, to end: Index) -> Int { - switch (start.representation, end.representation) { - case (.start, .start): - return 0 - case let (.start, .base(index, _)): - return base.distance(from: base.startIndex, to: index) - case (.start, .end): - return base.distance(from: base.startIndex, to: base.endIndex) - case let (.base(index, _), .start): - return base.distance(from: index, to: base.startIndex) - case let (.base(start, _), .base(end, _)): - return base.distance(from: start, to: end) - case let (.base(index, _), .end): - return base.distance(from: index, to: base.endIndex) - case (.end, .start): - return base.distance(from: base.endIndex, to: base.startIndex) - case let (.end, .base(index, _)): - return base.distance(from: base.endIndex, to: index) - case (.end, .end): - return 0 - } + base.distance(from: start.base, to: end.base) } } -extension InclusiveReductions: LazySequenceProtocol - where Base: LazySequenceProtocol {} +extension InclusiveReductionsSequence: LazySequenceProtocol {} -extension InclusiveReductions: LazyCollectionProtocol - where Base: LazyCollectionProtocol {} +extension InclusiveReductionsSequence: LazyCollectionProtocol + where Base: Collection {} -// MARK: - ReductionsIndexRepresentation - -@usableFromInline -enum ReductionsIndexRepresentation { - case start - case base(index: BaseIndex, result: Result) - case end -} - -extension ReductionsIndexRepresentation: Equatable { +extension InclusiveReductionsSequence.Index: Hashable + where Base.Index: Hashable +{ @inlinable - static func == (lhs: Self, rhs: Self) -> Bool { - switch (lhs, rhs) { - case (.start, .start): return true - case (.end, .end): return true - case let (.base(lhs, _), .base(rhs, _)): return lhs == rhs - default: return false - } - } -} - -extension ReductionsIndexRepresentation: Comparable { - @inlinable - static func < (lhs: Self, rhs: Self) -> Bool { - switch (lhs, rhs) { - case (_, .start): return false - case (.start, _): return true - case (.end, _): return false - case (_, .end): return true - case let (.base(lhs, _), .base(rhs, _)): return lhs < rhs - } + public func hash(into hasher: inout Hasher) { + hasher.combine(base) } } // MARK: - Scan extension LazySequenceProtocol { - @available(*, deprecated, message: "Use reductions(_:_:) instead.") @inlinable public func scan( _ initial: Result, _ transform: @escaping (Result, Element) -> Result - ) -> ExclusiveReductions { + ) -> ExclusiveReductionsSequence { reductions(initial, transform) } @@ -594,13 +574,12 @@ extension LazySequenceProtocol { public func scan( into initial: Result, _ transform: @escaping (inout Result, Element) -> Void - ) -> ExclusiveReductions { + ) -> ExclusiveReductionsSequence { reductions(into: initial, transform) } } extension Sequence { - @available(*, deprecated, message: "Use reductions(_:_:) instead.") @inlinable public func scan( @@ -621,18 +600,16 @@ extension Sequence { } extension LazySequenceProtocol { - @available(*, deprecated, message: "Use reductions(_:) instead.") @inlinable public func scan( _ transform: @escaping (Element, Element) -> Element - ) -> InclusiveReductions { + ) -> InclusiveReductionsSequence { reductions(transform) } } extension Sequence { - @available(*, deprecated, message: "Use reductions(_:) instead.") @inlinable public func scan( diff --git a/Sources/Algorithms/Rotate.swift b/Sources/Algorithms/Rotate.swift index 094b1d9..4d0fa0c 100644 --- a/Sources/Algorithms/Rotate.swift +++ b/Sources/Algorithms/Rotate.swift @@ -75,8 +75,8 @@ extension MutableCollection where Self: BidirectionalCollection { extension MutableCollection { /// Swaps the elements of the two given subranges, up to the upper bound of - /// the smaller subrange. The returned indices are the ends of the two - /// ranges that were actually swapped. + /// the smaller subrange. The returned indices are the ends of the two ranges + /// that were actually swapped. /// /// Input: /// [a b c d e f g h i j k l m n o p] @@ -112,8 +112,8 @@ extension MutableCollection { return (p, q) } - /// Rotates the elements within the given subrange so that the element - /// at the specified index becomes the start of the subrange. + /// Rotates the elements within the given subrange so that the element at the + /// specified index becomes the start of the subrange. /// /// Rotating a collection is equivalent to breaking the collection into two /// sections at the index `newStart`, and then swapping those two sections. @@ -146,10 +146,9 @@ extension MutableCollection { if s == m { return e } if m == e { return s } - // We have two regions of possibly-unequal length that need to be - // exchanged. The return value of this method is going to be the - // position following that of the element that is currently last - // (element j). + // We have two regions of possibly-unequal length that need to be exchanged. + // The return value of this method is going to be the position following + // that of the element that is currently last (element j). // // [a b c d e f g|h i j] or [a b c|d e f g h i j] // ^ ^ ^ ^ ^ ^ @@ -157,8 +156,8 @@ extension MutableCollection { // var ret = e // start with a known incorrect result. while true { - // Exchange the leading elements of each region (up to the - // length of the shorter region). + // Exchange the leading elements of each region (up to the length of the + // shorter region). // // [a b c d e f g|h i j] or [a b c|d e f g h i j] // ^^^^^ ^^^^^ ^^^^^ ^^^^^ @@ -169,21 +168,20 @@ extension MutableCollection { let (s1, m1) = _swapNonemptySubrangePrefixes(s.., - at newStart: Index) -> Index - { - rotate(subrange: subrange, toStartAt: newStart) - } - - @available(*, deprecated, renamed: "rotate(toStartAt:)") - @discardableResult - public mutating func rotate(at newStart: Index) -> Index { - rotate(toStartAt: newStart) - } -} diff --git a/Sources/Algorithms/LazySplit.swift b/Sources/Algorithms/Split.swift similarity index 96% rename from Sources/Algorithms/LazySplit.swift rename to Sources/Algorithms/Split.swift index 9241e63..a1e941a 100644 --- a/Sources/Algorithms/LazySplit.swift +++ b/Sources/Algorithms/Split.swift @@ -10,8 +10,9 @@ //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// -// LazySplitSequence +// SplitSequence //===----------------------------------------------------------------------===// + /// A sequence that lazily splits a base sequence into subsequences separated by /// elements that satisfy the given `whereSeparator` predicate. /// @@ -21,7 +22,7 @@ /// x.split(separator:maxSplits:omittingEmptySubsequences) /// /// where `x` conforms to `LazySequenceProtocol`. -public struct LazySplitSequence { +public struct SplitSequence { @usableFromInline internal let base: Base @@ -48,7 +49,7 @@ public struct LazySplitSequence { } } -extension LazySplitSequence { +extension SplitSequence: Sequence { public struct Iterator { public typealias Element = [Base.Element] @@ -85,9 +86,19 @@ extension LazySplitSequence { self.omittingEmptySubsequences = omittingEmptySubsequences } } + + @inlinable + public func makeIterator() -> Iterator { + Iterator( + base: base.makeIterator(), + whereSeparator: self.isSeparator, + maxSplits: self.maxSplits, + omittingEmptySubsequences: self.omittingEmptySubsequences + ) + } } -extension LazySplitSequence.Iterator: IteratorProtocol { +extension SplitSequence.Iterator: IteratorProtocol { @inlinable public mutating func next() -> Element? { var currentElement = base.next() @@ -128,17 +139,7 @@ extension LazySplitSequence.Iterator: IteratorProtocol { } } -extension LazySplitSequence: LazySequenceProtocol { - @inlinable - public func makeIterator() -> Iterator { - return Iterator( - base: base.makeIterator(), - whereSeparator: self.isSeparator, - maxSplits: self.maxSplits, - omittingEmptySubsequences: self.omittingEmptySubsequences - ) - } -} +extension SplitSequence: LazySequenceProtocol {} extension LazySequenceProtocol { /// Lazily returns the longest possible subsequences of the sequence, in @@ -230,10 +231,10 @@ extension LazySequenceProtocol { maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: @escaping (Element) -> Bool - ) -> LazySplitSequence { + ) -> SplitSequence { precondition(maxSplits >= 0, "Must take zero or more splits") - return LazySplitSequence( + return SplitSequence( base: elements, isSeparator: isSeparator, maxSplits: maxSplits, @@ -320,10 +321,10 @@ extension LazySequenceProtocol where Element: Equatable { separator: Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true - ) -> LazySplitSequence { + ) -> SplitSequence { precondition(maxSplits >= 0, "Must take zero or more splits") - return LazySplitSequence( + return SplitSequence( base: elements, isSeparator: { $0 == separator }, maxSplits: maxSplits, @@ -333,8 +334,9 @@ extension LazySequenceProtocol where Element: Equatable { } //===----------------------------------------------------------------------===// -// LazySplitCollection +// SplitCollection //===----------------------------------------------------------------------===// + /// A collection that lazily splits a base collection into subsequences /// separated by elements that satisfy the given `whereSeparator` predicate. /// @@ -343,8 +345,8 @@ extension LazySequenceProtocol where Element: Equatable { /// x.split(maxSplits:omittingEmptySubsequences:whereSeparator) /// x.split(separator:maxSplits:omittingEmptySubsequences) /// -/// where `x` conforms to `LazyCollectionProtocol`. -public struct LazySplitCollection { +/// where `x` conforms to `LazySequenceProtocol` and `Collection`. +public struct SplitCollection { @usableFromInline internal let base: Base @@ -398,7 +400,7 @@ public struct LazySplitCollection { } } -extension LazySplitCollection: LazyCollectionProtocol { +extension SplitCollection: Collection { /// Position of a subsequence in a split collection. public struct Index: Comparable { /// The range corresponding to the subsequence at this position. @@ -475,7 +477,7 @@ extension LazySplitCollection: LazyCollectionProtocol { } var updatedSplitCount = splitCount - if end < base.endIndex { + if end != base.endIndex { // This subsequence ends on a separator (and perhaps includes other // separators, if we're omitting empty subsequences), so we've performed // another split. @@ -547,13 +549,16 @@ extension LazySplitCollection: LazyCollectionProtocol { } } -extension LazySplitCollection.Index: Hashable { +extension SplitCollection.Index: Hashable { + @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(sequenceLength) } } -extension LazyCollectionProtocol { +extension SplitCollection: LazyCollectionProtocol {} + +extension LazySequenceProtocol where Self: Collection, Elements: Collection { /// Lazily returns the longest possible subsequences of the collection, in /// order, that don't contain elements satisfying the given predicate. /// @@ -641,10 +646,10 @@ extension LazyCollectionProtocol { maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: @escaping (Element) -> Bool - ) -> LazySplitCollection { + ) -> SplitCollection { precondition(maxSplits >= 0, "Must take zero or more splits") - return LazySplitCollection( + return SplitCollection( base: elements, isSeparator: isSeparator, maxSplits: maxSplits, @@ -653,8 +658,9 @@ extension LazyCollectionProtocol { } } -extension LazyCollectionProtocol -where Element: Equatable { +extension LazySequenceProtocol + where Self: Collection, Elements: Collection, Element: Equatable +{ /// Lazily returns the longest possible subsequences of the collection, in /// order, around elements equal to the given element. /// @@ -737,10 +743,10 @@ where Element: Equatable { separator: Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true - ) -> LazySplitCollection { + ) -> SplitCollection { precondition(maxSplits >= 0, "Must take zero or more splits") - return LazySplitCollection( + return SplitCollection( base: elements, isSeparator: { $0 == separator }, maxSplits: maxSplits, diff --git a/Sources/Algorithms/Stride.swift b/Sources/Algorithms/Stride.swift index ba1f0d3..bf91612 100644 --- a/Sources/Algorithms/Stride.swift +++ b/Sources/Algorithms/Stride.swift @@ -14,47 +14,46 @@ //===----------------------------------------------------------------------===// extension Sequence { - /// Returns a sequence stepping through the elements every `step` starting - /// at the first value. Any remainders of the stride will be trimmed. + /// Returns a sequence stepping through the elements every `step` starting at + /// the first value. Any remainders of the stride will be trimmed. /// /// (0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10] /// (0...10).striding(by: 3) // == [0, 3, 6, 9] /// - /// - Complexity: O(1). Access to successive values is O(k) where - /// _k_ is the striding `step`. + /// - Complexity: O(1). Access to successive values is O(k) where _k_ is the + /// striding `step`. /// /// - Parameter step: The amount to step with each iteration. - /// - Returns: Returns a sequence for stepping through the - /// elements by the specified amount. + /// - Returns: Returns a sequence for stepping through the elements by the + /// specified amount. @inlinable - public func striding(by step: Int) -> StrideSequence { - StrideSequence(base: self, stride: step) + public func striding(by step: Int) -> StridingSequence { + StridingSequence(base: self, stride: step) } } extension Collection { - /// Returns a sequence stepping through the elements every `step` starting - /// at the first value. Any remainders of the stride will be trimmed. + /// Returns a sequence stepping through the elements every `step` starting at + /// the first value. Any remainders of the stride will be trimmed. /// /// (0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10] /// (0...10).striding(by: 3) // == [0, 3, 6, 9] /// - /// - Complexity: O(1). Access to successive values is O(1) if the - /// collection conforms to `RandomAccessCollection`; otherwise, - /// O(_k_), where _k_ is the striding `step`. + /// - Complexity: O(1). Access to successive values is O(1) if the collection + /// conforms to `RandomAccessCollection`; otherwise, O(_k_), where _k_ is + /// the striding `step`. /// /// - Parameter step: The amount to step with each iteration. - /// - Returns: Returns a collection for stepping through the - /// elements by the specified amount. + /// - Returns: Returns a collection for stepping through the elements by the + /// specified amount. @inlinable - public func striding(by step: Int) -> StrideCollection { - StrideCollection(base: self, stride: step) + public func striding(by step: Int) -> StridingCollection { + StridingCollection(base: self, stride: step) } } /// A wrapper that strides over a base sequence. -public struct StrideSequence: Sequence { - +public struct StridingSequence { @usableFromInline internal let base: Base @@ -63,15 +62,21 @@ public struct StrideSequence: Sequence { @inlinable internal init(base: Base, stride: Int) { - precondition(stride > 0, "striding must be greater than zero") + precondition(stride > 0, "Stride must be greater than zero") self.base = base self.stride = stride } } -extension StrideSequence { - - /// An iterator over a `Stride` sequence. +extension StridingSequence { + @inlinable + public func striding(by step: Int) -> Self { + Self(base: base, stride: stride * step) + } +} + +extension StridingSequence: Sequence { + /// An iterator over a `StridingSequence` instance. public struct Iterator: IteratorProtocol { @usableFromInline internal var iterator: Base.Iterator @@ -107,15 +112,11 @@ extension StrideSequence { } } -extension StrideSequence { - @inlinable - public func striding(by step: Int) -> Self { - Self(base: base, stride: stride * step) - } -} +extension StridingSequence: LazySequenceProtocol + where Base: LazySequenceProtocol {} /// A wrapper that strides over a base collection. -public struct StrideCollection { +public struct StridingCollection { @usableFromInline internal let base: Base @@ -130,16 +131,15 @@ public struct StrideCollection { } } -extension StrideCollection { +extension StridingCollection { @inlinable public func striding(by step: Int) -> Self { Self(base: base, stride: stride * step) } } -extension StrideCollection: Collection { - - /// A position in a `Stride` collection. +extension StridingCollection: Collection { + /// A position in a `StridingCollection` instance. public struct Index: Comparable { @usableFromInline internal let base: Base.Index @@ -172,7 +172,7 @@ extension StrideCollection: Collection { @inlinable public func index(after i: Index) -> Index { - precondition(i.base < base.endIndex, "Advancing past end index") + precondition(i.base != base.endIndex, "Advancing past end index") return index(i, offsetBy: 1) } @@ -255,8 +255,8 @@ extension StrideCollection: Collection { @inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index { - precondition(distance <= 0 || i.base < base.endIndex, "Advancing past end index") - precondition(distance >= 0 || i.base > base.startIndex, "Incrementing past start index") + precondition(distance <= 0 || i.base != base.endIndex, "Advancing past end index") + precondition(distance >= 0 || i.base != base.startIndex, "Incrementing past start index") let limit = distance > 0 ? endIndex : startIndex let idx = index(i, offsetBy: distance, limitedBy: limit) precondition(idx != nil, "The distance \(distance) is not valid for this collection") @@ -264,15 +264,20 @@ extension StrideCollection: Collection { } } -extension StrideCollection: BidirectionalCollection +extension StridingCollection: BidirectionalCollection where Base: RandomAccessCollection { @inlinable public func index(before i: Index) -> Index { - precondition(i.base > base.startIndex, "Incrementing past start index") + precondition(i.base != base.startIndex, "Incrementing past start index") return index(i, offsetBy: -1) } } -extension StrideCollection: RandomAccessCollection where Base: RandomAccessCollection {} -extension StrideCollection.Index: Hashable where Base.Index: Hashable {} +extension StridingCollection: RandomAccessCollection + where Base: RandomAccessCollection {} + +extension StridingCollection: LazySequenceProtocol, LazyCollectionProtocol + where Base: LazySequenceProtocol {} + +extension StridingCollection.Index: Hashable where Base.Index: Hashable {} diff --git a/Sources/Algorithms/Suffix.swift b/Sources/Algorithms/Suffix.swift index 56966c7..c091b82 100644 --- a/Sources/Algorithms/Suffix.swift +++ b/Sources/Algorithms/Suffix.swift @@ -17,10 +17,10 @@ extension BidirectionalCollection { /// Returns a subsequence containing the elements from the end until /// `predicate` returns `false` and skipping the remaining elements. /// - /// - Parameter predicate: A closure that takes an element of the - /// sequence as its argument and returns `true` if the element should - /// be included or `false` if it should be excluded. Once the predicate - /// returns `false` it will not be called again. + /// - Parameter predicate: A closure that takes an element of the sequence as + /// its argument and returns `true` if the element should be included or + /// `false` if it should be excluded. Once the predicate returns `false` it + /// will not be called again. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable diff --git a/Sources/Algorithms/Trim.swift b/Sources/Algorithms/Trim.swift index 9771f91..832216b 100644 --- a/Sources/Algorithms/Trim.swift +++ b/Sources/Algorithms/Trim.swift @@ -13,18 +13,17 @@ //===----------------------------------------------------------------------===// extension Collection { - /// Returns a `SubSequence` formed by discarding all elements at the start - /// of the collection which satisfy the given predicate. + /// 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: + /// 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. + /// - Parameter predicate: A closure which determines if the element should be + /// omitted from the resulting slice. /// /// - Complexity: O(*n*), where *n* is the length of this collection. /// @@ -33,7 +32,7 @@ extension Collection { while predicate: (Element) throws -> Bool ) rethrows -> SubSequence { let start = try endOfPrefix(while: predicate) - return self[start.. Bool ) rethrows -> SubSequence { - return try trimmingPrefix(while: predicate).trimmingSuffix(while: predicate) + 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. + /// 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: + /// 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. + /// - Parameter predicate: A closure which determines if the element should be + /// omitted from the resulting slice. /// /// - Complexity: O(*n*), where *n* is the length of this collection. /// @@ -140,7 +135,7 @@ extension BidirectionalCollection { while predicate: (Element) throws -> Bool ) rethrows -> SubSequence { let end = try startOfSuffix(while: predicate) - return self[startIndex.. Bool ) rethrows { - replaceSubrange(startIndex.. { +public struct UniquedSequence { /// The base collection. @usableFromInline internal let base: Base @@ -26,8 +26,8 @@ public struct Uniqued { } } -extension Uniqued: Sequence { - /// The iterator for a `Uniqued` sequence. +extension UniquedSequence: Sequence { + /// The iterator for a `UniquedSequence` instance. public struct Iterator: IteratorProtocol { @usableFromInline internal var base: Base.Iterator @@ -64,7 +64,8 @@ extension Uniqued: Sequence { } } -extension Uniqued: LazySequenceProtocol where Base: LazySequenceProtocol {} +extension UniquedSequence: LazySequenceProtocol + where Base: LazySequenceProtocol {} //===----------------------------------------------------------------------===// // uniqued() @@ -83,8 +84,8 @@ extension Sequence where Element: Hashable { /// . /// - Complexity: O(1). @inlinable - public func uniqued() -> Uniqued { - Uniqued(base: self, projection: { $0 }) + public func uniqued() -> UniquedSequence { + UniquedSequence(base: self, projection: { $0 }) } } @@ -102,9 +103,9 @@ extension Sequence { /// // Prints '["dog", "pig", "cat", "ox"]' /// /// - Parameter projection: A closure that transforms an element into the - /// value to use for uniqueness. If `projection` returns the same value - /// for two different elements, the second element will be excluded - /// from the resulting array. + /// value to use for uniqueness. If `projection` returns the same value for + /// two different elements, the second element will be excluded from the + /// resulting array. /// /// - Returns: An array with only the unique elements of this sequence, as /// determined by the result of `projection` for each element. @@ -138,7 +139,7 @@ extension LazySequenceProtocol { @inlinable public func uniqued( on projection: @escaping (Element) -> Subject - ) -> Uniqued { - Uniqued(base: self, projection: projection) + ) -> UniquedSequence { + UniquedSequence(base: self, projection: projection) } } diff --git a/Sources/Algorithms/Windows.swift b/Sources/Algorithms/Windows.swift index 6d8e269..bee7b86 100644 --- a/Sources/Algorithms/Windows.swift +++ b/Sources/Algorithms/Windows.swift @@ -39,35 +39,35 @@ extension Collection { /// `RandomAccessCollection`, otherwise O(*k*) where `k` is `count`. /// Access to successive windows is O(1). @inlinable - public func windows(ofCount count: Int) -> Windows { - Windows(base: self, size: count) + public func windows(ofCount count: Int) -> WindowsOfCountCollection { + WindowsOfCountCollection(base: self, windowSize: count) } } /// A collection wrapper that presents a sliding window over the elements of /// a collection. -public struct Windows { +public struct WindowsOfCountCollection { @usableFromInline internal let base: Base @usableFromInline - internal let size: Int + internal let windowSize: Int @usableFromInline - internal var firstUpperBound: Base.Index? + internal var endOfFirstWindow: Base.Index? @inlinable - internal init(base: Base, size: Int) { - precondition(size > 0, "Windows size must be greater than zero") + internal init(base: Base, windowSize: Int) { + precondition(windowSize > 0, "Windows size must be greater than zero") self.base = base - self.size = size - self.firstUpperBound = - base.index(base.startIndex, offsetBy: size, limitedBy: base.endIndex) + self.windowSize = windowSize + self.endOfFirstWindow = + base.index(base.startIndex, offsetBy: windowSize, limitedBy: base.endIndex) } } -extension Windows: Collection { - /// A position in a `Windows` collection. +extension WindowsOfCountCollection: Collection { + /// A position in a `WindowsOfCountCollection` instance. public struct Index: Comparable { @usableFromInline internal var lowerBound: Base.Index @@ -94,7 +94,7 @@ extension Windows: Collection { @inlinable public var startIndex: Index { - if let upperBound = firstUpperBound { + if let upperBound = endOfFirstWindow { return Index(lowerBound: base.startIndex, upperBound: upperBound) } else { return endIndex @@ -116,12 +116,14 @@ extension Windows: Collection { @inlinable public func index(after index: Index) -> Index { - precondition(index < endIndex, "Advancing past end index") + precondition(index != endIndex, "Advancing past end index") guard index.upperBound < base.endIndex else { return endIndex } - return Index( - lowerBound: base.index(after: index.lowerBound), - upperBound: base.index(after: index.upperBound) - ) + + let lowerBound = windowSize == 1 + ? index.upperBound + : base.index(after: index.lowerBound) + let upperBound = base.index(after: index.upperBound) + return Index(lowerBound: lowerBound, upperBound: upperBound) } @inlinable @@ -185,7 +187,7 @@ extension Windows: Collection { // |> > >|>| or |> > >| // output: [x x x x x|x x x x x] [x x x x x x x x x x] (`endIndex`) - if distance >= size { + if distance >= windowSize { // Avoid traversing `self[i.lowerBound..= i.upperBound, let lowerBound = base.index( i.upperBound, - offsetBy: distance - size, + offsetBy: distance - windowSize, limitedBy: limit.lowerBound), let indexBeforeUpperBound = base.index( lowerBound, - offsetBy: size - 1, + offsetBy: windowSize - 1, limitedBy: limit.upperBound) else { return nil } @@ -262,9 +264,9 @@ extension Windows: Collection { else { return nil } return Index( - lowerBound: base.index(upperBound, offsetBy: -size), + lowerBound: base.index(upperBound, offsetBy: -windowSize), upperBound: upperBound) - } else if distance >= size { + } else if distance >= windowSize { // Avoid traversing `self[i.lowerBound.. Int { guard start <= end else { return -distance(from: end, to: start) } guard start != end else { return 0 } - guard end < endIndex else { + guard end != endIndex else { // We add 1 here because the index before `endIndex` also has // `base.endIndex` as its upper bound. return base[start.upperBound...].count + 1 @@ -318,7 +320,7 @@ extension Windows: Collection { // |- - - -|> >| // end: [x x x x x x x|x x x x|x] - return size + base[start.upperBound.. > > >| @@ -329,13 +331,15 @@ extension Windows: Collection { } } -extension Windows: BidirectionalCollection where Base: BidirectionalCollection { +extension WindowsOfCountCollection: BidirectionalCollection + where Base: BidirectionalCollection +{ @inlinable public func index(before index: Index) -> Index { - precondition(index > startIndex, "Incrementing past start index") + precondition(index != startIndex, "Incrementing past start index") if index == endIndex { return Index( - lowerBound: base.index(index.lowerBound, offsetBy: -size), + lowerBound: base.index(index.lowerBound, offsetBy: -windowSize), upperBound: index.upperBound ) } else { @@ -347,7 +351,10 @@ extension Windows: BidirectionalCollection where Base: BidirectionalCollection { } } -extension Windows: LazySequenceProtocol where Base: LazySequenceProtocol {} -extension Windows: LazyCollectionProtocol where Base: LazyCollectionProtocol {} -extension Windows: RandomAccessCollection where Base: RandomAccessCollection {} -extension Windows.Index: Hashable where Base.Index: Hashable {} +extension WindowsOfCountCollection: RandomAccessCollection + where Base: RandomAccessCollection {} + +extension WindowsOfCountCollection: LazySequenceProtocol, LazyCollectionProtocol + where Base: LazySequenceProtocol {} + +extension WindowsOfCountCollection.Index: Hashable where Base.Index: Hashable {} diff --git a/Tests/SwiftAlgorithmsTests/AdjacentPairsTests.swift b/Tests/SwiftAlgorithmsTests/AdjacentPairsTests.swift index 98396aa..f07fe52 100644 --- a/Tests/SwiftAlgorithmsTests/AdjacentPairsTests.swift +++ b/Tests/SwiftAlgorithmsTests/AdjacentPairsTests.swift @@ -70,11 +70,11 @@ final class AdjacentPairsTests: XCTestCase { } func testIndexTraversals() { - validateIndexTraversals( - (0..<0).adjacentPairs(), - (0..<1).adjacentPairs(), - (0..<2).adjacentPairs(), - (0..<5).adjacentPairs()) + let validator = IndexValidator>>() + validator.validate((0..<0).adjacentPairs(), expectedCount: 0) + validator.validate((0..<1).adjacentPairs(), expectedCount: 0) + validator.validate((0..<2).adjacentPairs(), expectedCount: 1) + validator.validate((0..<5).adjacentPairs(), expectedCount: 4) } func testLaziness() { diff --git a/Tests/SwiftAlgorithmsTests/ChainTests.swift b/Tests/SwiftAlgorithmsTests/ChainTests.swift index 104a6a2..6183cf3 100644 --- a/Tests/SwiftAlgorithmsTests/ChainTests.swift +++ b/Tests/SwiftAlgorithmsTests/ChainTests.swift @@ -36,16 +36,17 @@ final class ChainTests: XCTestCase { } func testChainIndexTraversals() { - validateIndexTraversals( - chain("abcd", "XYZ"), - chain("abcd", ""), - chain("", "XYZ"), - chain("", ""), - indices: { chain in + let validator = IndexValidator>( + indicesIncludingEnd: { chain in chain.base1.indices.map { .init(first: $0) } + chain.base2.indices.map { .init(second: $0) } + [.init(second: chain.base2.endIndex)] }) + + validator.validate(chain("abcd", "XYZ"), expectedCount: 4 + 3) + validator.validate(chain("abcd", ""), expectedCount: 4 + 0) + validator.validate(chain("", "XYZ"), expectedCount: 0 + 3) + validator.validate(chain("", ""), expectedCount: 0 + 0) } func testChainIndexOffsetAcrossBoundary() { diff --git a/Tests/SwiftAlgorithmsTests/ChunkedTests.swift b/Tests/SwiftAlgorithmsTests/ChunkedTests.swift index 56a7a6f..811f787 100644 --- a/Tests/SwiftAlgorithmsTests/ChunkedTests.swift +++ b/Tests/SwiftAlgorithmsTests/ChunkedTests.swift @@ -67,7 +67,7 @@ final class ChunkedTests: XCTestCase { let lazyChunks = fruits.lazy.chunked(on: { $0.first }) validateFruitChunks(lazyChunks.map { $1 }) - validateIndexTraversals(lazyChunks) + IndexValidator().validate(lazyChunks) } func testChunkedBy() { @@ -75,7 +75,7 @@ final class ChunkedTests: XCTestCase { let lazyChunks = fruits.lazy.chunked(by: { $0.first == $1.first }) validateFruitChunks(lazyChunks) - validateIndexTraversals(lazyChunks) + IndexValidator().validate(lazyChunks) } func testChunkedByComparesConsecutiveElements() { @@ -94,7 +94,7 @@ final class ChunkedTests: XCTestCase { [1, 2, 3, 4, 6, 7, 8, 9].lazy.chunked(by: { $1 - $0 == 1 }).reversed(), [[6, 7, 8, 9], [1, 2, 3, 4]]) - validateIndexTraversals([1, 2, 3].lazy.chunked(by: { $1 - $0 == 1 })) + IndexValidator().validate([1, 2, 3].lazy.chunked(by: { $1 - $0 == 1 })) } func testChunkedLazy() { @@ -159,15 +159,18 @@ final class ChunkedTests: XCTestCase { func testEmptyChunksOfCountTraversal() { let emptyChunks = [Int]().chunks(ofCount: 1) - validateIndexTraversals(emptyChunks) + IndexValidator().validate(emptyChunks, expectedCount: 0) } func testChunksOfCountTraversal() { - for i in 1..<10 { - let collection = (1...50).map { $0 } - let chunks = collection.chunks(ofCount: i) - - validateIndexTraversals(chunks) + let validator = IndexValidator>>() + + for i in 1...10 { + let range = 1...50 + let chunks = range.chunks(ofCount: i) + validator.validate( + chunks, + expectedCount: range.count / i + (range.count % i).signum()) } } } diff --git a/Tests/SwiftAlgorithmsTests/CompactedTests.swift b/Tests/SwiftAlgorithmsTests/CompactedTests.swift index dbff888..a23d015 100644 --- a/Tests/SwiftAlgorithmsTests/CompactedTests.swift +++ b/Tests/SwiftAlgorithmsTests/CompactedTests.swift @@ -37,8 +37,9 @@ final class CompactedTests: XCTestCase { } func testCollectionTraversals() { + let validator = IndexValidator>() for array in self.tests { - validateIndexTraversals(array.compacted()) + validator.validate(array.compacted()) } } } diff --git a/Tests/SwiftAlgorithmsTests/IntersperseTests.swift b/Tests/SwiftAlgorithmsTests/IntersperseTests.swift index 50baa69..49c1376 100644 --- a/Tests/SwiftAlgorithmsTests/IntersperseTests.swift +++ b/Tests/SwiftAlgorithmsTests/IntersperseTests.swift @@ -26,25 +26,21 @@ final class IntersperseTests: XCTestCase { func testString() { let interspersed = "ABCDE".interspersed(with: "-") XCTAssertEqualSequences(interspersed, "A-B-C-D-E") - validateIndexTraversals(interspersed) } func testStringEmpty() { let interspersed = "".interspersed(with: "-") XCTAssertEqualSequences(interspersed, "") - validateIndexTraversals(interspersed) } func testArray() { let interspersed = [1,2,3,4].interspersed(with: 0) XCTAssertEqualSequences(interspersed, [1,0,2,0,3,0,4]) - validateIndexTraversals(interspersed) } func testArrayEmpty() { let interspersed = [].interspersed(with: 0) XCTAssertEqualSequences(interspersed, []) - validateIndexTraversals(interspersed) } func testCollection() { @@ -55,7 +51,14 @@ final class IntersperseTests: XCTestCase { func testBidirectionalCollection() { let reversed = "ABCDE".interspersed(with: "-").reversed() XCTAssertEqualSequences(reversed, "E-D-C-B-A") - validateIndexTraversals(reversed) + } + + func testIndexTraversals() { + let validator = IndexValidator>() + validator.validate("".interspersed(with: "-"), expectedCount: 0) + validator.validate("A".interspersed(with: "-"), expectedCount: 1) + validator.validate("AB".interspersed(with: "-"), expectedCount: 3) + validator.validate("ABCDE".interspersed(with: "-"), expectedCount: 9) } func testIntersperseLazy() { @@ -83,10 +86,18 @@ final class IntersperseTests: XCTestCase { } 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 })) + let validator = IndexValidator, Int>>() + validator.validate( + (0..<0).lazy.interspersedMap({ $0 }, with: {_, _ in 100 }), + expectedCount: 0) + validator.validate( + (0..<1).lazy.interspersedMap({ $0 }, with: {_, _ in 100 }), + expectedCount: 1) + validator.validate( + (0..<2).lazy.interspersedMap({ $0 }, with: {_, _ in 100 }), + expectedCount: 3) + validator.validate( + (0..<5).lazy.interspersedMap({ $0 }, with: {_, _ in 100 }), + expectedCount: 9) } } diff --git a/Tests/SwiftAlgorithmsTests/JoinedTests.swift b/Tests/SwiftAlgorithmsTests/JoinedTests.swift index cb70558..690659e 100644 --- a/Tests/SwiftAlgorithmsTests/JoinedTests.swift +++ b/Tests/SwiftAlgorithmsTests/JoinedTests.swift @@ -111,15 +111,22 @@ final class JoinedTests: XCTestCase { } func testJoinedIndexTraversals() { + let validator = IndexValidator>() + // the last test case takes too long to run for strings in stringArrays.dropLast() { - validateIndexTraversals(strings.joined() as FlattenCollection) - validateIndexTraversals(strings.joined(by: ", ")) + validator.validate(strings.joined() as FlattenCollection) } + } + + func testJoinedByIndexTraversals() { + let validator1 = IndexValidator>() + let validator2 = IndexValidator>() + // the last test case takes too long to run for (strings, separator) in product(stringArrays.dropLast(), ["", " ", ", "]) { - validateIndexTraversals(strings.joined(by: separator)) - validateIndexTraversals(strings.lazy.joined(by: { _, _ in separator })) + validator1.validate(strings.joined(by: separator)) + validator2.validate(strings.lazy.joined(by: { _, _ in separator })) } } } diff --git a/Tests/SwiftAlgorithmsTests/ProductTests.swift b/Tests/SwiftAlgorithmsTests/ProductTests.swift index 37b434f..b04932e 100644 --- a/Tests/SwiftAlgorithmsTests/ProductTests.swift +++ b/Tests/SwiftAlgorithmsTests/ProductTests.swift @@ -39,17 +39,18 @@ final class ProductTests: XCTestCase { } func testProductIndexTraversals() { - validateIndexTraversals( - product([1, 2, 3, 4], "abc"), - product([1, 2, 3, 4], ""), - product([], "abc"), - product([], ""), - indices: { product in + let validator = IndexValidator>( + indicesIncludingEnd: { product in product.base1.indices.flatMap { i1 in product.base2.indices.map { i2 in .init(i1: i1, i2: i2) } } + [.init(i1: product.base1.endIndex, i2: product.base2.startIndex)] }) + + validator.validate(product([1, 2, 3, 4], "abc"), expectedCount: 4 * 3) + validator.validate(product([1, 2, 3, 4], ""), expectedCount: 4 * 0) + validator.validate(product([], "abc"), expectedCount: 0 * 3) + validator.validate(product([], ""), expectedCount: 0 * 0) } } diff --git a/Tests/SwiftAlgorithmsTests/ReductionsTests.swift b/Tests/SwiftAlgorithmsTests/ReductionsTests.swift index f3490cc..76322d3 100644 --- a/Tests/SwiftAlgorithmsTests/ReductionsTests.swift +++ b/Tests/SwiftAlgorithmsTests/ReductionsTests.swift @@ -13,7 +13,6 @@ import XCTest import Algorithms final class ReductionsTests: XCTestCase { - struct TestError: Error {} // MARK: - Exclusive Reductions @@ -52,6 +51,13 @@ final class ReductionsTests: XCTestCase { XCTAssertNoThrow(try [].reductions(0) { _, _ in throw TestError() }) XCTAssertThrowsError(try [1].reductions(0) { _, _ in throw TestError() }) } + + func testExclusiveIndexTraversals() { + let validator = IndexValidator, Int>>() + validator.validate((0..<0).lazy.reductions(0, +), expectedCount: 1) + validator.validate((0..<1).lazy.reductions(0, +), expectedCount: 2) + validator.validate((0..<4).lazy.reductions(0, +), expectedCount: 5) + } // MARK: - Inclusive Reductions @@ -78,4 +84,11 @@ final class ReductionsTests: XCTestCase { XCTAssertNoThrow(try [1].reductions { _, _ in throw TestError() }) XCTAssertThrowsError(try [1, 1].reductions { _, _ in throw TestError() }) } + + func testInclusiveIndexTraversals() { + let validator = IndexValidator>>() + validator.validate((0..<0).lazy.reductions(+), expectedCount: 0) + validator.validate((0..<1).lazy.reductions(+), expectedCount: 1) + validator.validate((0..<4).lazy.reductions(+), expectedCount: 4) + } } diff --git a/Tests/SwiftAlgorithmsTests/LazySplitTests.swift b/Tests/SwiftAlgorithmsTests/SplitTests.swift similarity index 99% rename from Tests/SwiftAlgorithmsTests/LazySplitTests.swift rename to Tests/SwiftAlgorithmsTests/SplitTests.swift index 34cdfe7..f0adad5 100644 --- a/Tests/SwiftAlgorithmsTests/LazySplitTests.swift +++ b/Tests/SwiftAlgorithmsTests/SplitTests.swift @@ -13,10 +13,10 @@ import Algorithms import XCTest //===----------------------------------------------------------------------===// -// Tests for `LazySplitSequence` and `LazySplitCollection` +// Tests for `SplitSequence` and `SplitCollection` //===----------------------------------------------------------------------===// -final class LazySplitTests: XCTestCase { +final class SplitTests: XCTestCase { func testEmpty() { Validator( subject: [], diff --git a/Tests/SwiftAlgorithmsTests/StrideTests.swift b/Tests/SwiftAlgorithmsTests/StrideTests.swift index 6143a46..cdeeafa 100644 --- a/Tests/SwiftAlgorithmsTests/StrideTests.swift +++ b/Tests/SwiftAlgorithmsTests/StrideTests.swift @@ -88,31 +88,37 @@ final class StridingTests: XCTestCase { } func testIndexTraversals() { - let empty = [Int]() - validateIndexTraversals( - empty.striding(by: 1), - empty.striding(by: 2) - ) - let zero_to_one_hundered_range = 0...100 - validateIndexTraversals( - zero_to_one_hundered_range.striding(by: 10), - zero_to_one_hundered_range.striding(by: 11), - zero_to_one_hundered_range.striding(by: 101) - ) - let zero_to_one_hundered_array = Array(zero_to_one_hundered_range) - validateIndexTraversals( - zero_to_one_hundered_array.striding(by: 10), - zero_to_one_hundered_array.striding(by: 11), - zero_to_one_hundered_array.striding(by: 101) - ) - let string = "swift rocks".map(String.init) - validateIndexTraversals( - string.striding(by: 1), - string.striding(by: 2), - string.striding(by: 10) - ) + do { + let empty = [Int]() + let validator = IndexValidator>() + validator.validate(empty.striding(by: 1)) + validator.validate(empty.striding(by: 2)) + } + + do { + let range = 0...100 + let validator = IndexValidator>>() + validator.validate(range.striding(by: 10)) + validator.validate(range.striding(by: 11)) + validator.validate(range.striding(by: 101)) + } + + do { + let array = Array(0...100) + let validator = IndexValidator>() + validator.validate(array.striding(by: 10)) + validator.validate(array.striding(by: 11)) + validator.validate(array.striding(by: 101)) + } + + do { + let string = "swift rocks" + let validator = IndexValidator>() + validator.validate(string.striding(by: 1)) + validator.validate(string.striding(by: 2)) + validator.validate(string.striding(by: 10)) + } } - func testOffsetBy() { let a = (0...100).striding(by: 22) @@ -128,4 +134,10 @@ final class StridingTests: XCTestCase { let i = b.index(b.startIndex, offsetBy: 2) XCTAssertEqual(i, b.endIndex) } + + func testLazy() { + XCTAssertLazySequence(AnySequence(0..<100).lazy.striding(by: 3)) + XCTAssertLazySequence((0..<100).lazy.striding(by: 3)) + XCTAssertLazyCollection((0..<100).lazy.striding(by: 3)) + } } diff --git a/Tests/SwiftAlgorithmsTests/TestUtilities.swift b/Tests/SwiftAlgorithmsTests/TestUtilities.swift index 6322a99..68870bb 100644 --- a/Tests/SwiftAlgorithmsTests/TestUtilities.swift +++ b/Tests/SwiftAlgorithmsTests/TestUtilities.swift @@ -59,7 +59,7 @@ extension AnyMutableCollection: MutableCollection { var endIndex: Base.Index { base.endIndex } func index(after i: Index) -> Index { - return base.index(after: i) + base.index(after: i) } subscript(position: Base.Index) -> Base.Element { @@ -163,93 +163,162 @@ func XCTAssertEqualCollections( } } -/// Tests that all index traversal methods behave as expected. -/// -/// Verifies the correctness of the implementations of `startIndex`, `endIndex`, -/// `indices`, `count`, `isEmpty`, `index(before:)`, `index(after:)`, -/// `index(_:offsetBy:)`, `index(_:offsetBy:limitedBy:)`, and -/// `distance(from:to:)` by calling them with just about all possible input -/// combinations. When provided, the `indices` function is used to to test the -/// collection methods against. -/// -/// - Parameters: -/// - collections: The collections to be validated. -/// - indices: A closure that returns the expected indices of the given -/// collection, including its `endIndex`, in ascending order. Only use this -/// parameter if you are able to compute the indices of the collection -/// independently of the `Collection` conformance, e.g. by using the -/// contents of the collection directly. -/// -/// - Complexity: O(*n*^3) for each collection, where *n* is the length of the -/// collection. -func validateIndexTraversals( - _ collections: C..., - indices: ((C) -> [C.Index])? = nil, - file: StaticString = #file, line: UInt = #line -) where C: BidirectionalCollection { - for c in collections { - let indicesIncludingEnd = indices?(c) ?? (c.indices + [c.endIndex]) +struct IndexValidator { + let testRandomAccess = true + let indicesIncludingEnd: (C) -> [C.Index] + + /// Creates a new instance of an index validator that can verify that indices + /// of a collection behave correctly and consistently. + /// + /// Usage: + /// + /// let validator = IndexValidator>() + /// validator.validate("abc".reversed()) + /// validator.validate("xyz".reversed(), expectedCount: 3) + /// + /// - Parameters: + /// - testRandomAccess: If `true`, also tests the correctness of the methods + /// `index(_:offsetBy:)`, `index(_:offsetBy:limitedBy:)`, and + /// `distance(from:to:)`. Only useful if the collection overrides these + /// methods. Defaults to `true`. + /// - indicesIncludingEnd: A closure that returns the expected indices of + /// the given collection, including its `endIndex`, in ascending order. + /// Only use this parameter if you are able to compute the indices of the + /// collection independently of the `Collection` conformance, e.g. by + /// using the contents of the collection directly. + init( + testRandomAccess: Bool = true, + indicesIncludingEnd: @escaping (C) -> [C.Index] = { $0.indices + [$0.endIndex] } + ) { + self.indicesIncludingEnd = indicesIncludingEnd + } +} + +extension IndexValidator { + fileprivate struct Validator { + let collection: C + let count: Int + let indicesIncludingEnd: [C.Index] + let file: StaticString + let line: UInt + } + + /// Verifies that all index traversal methods behave as expected. + /// + /// Verifies the correctness of the implementations of `startIndex`, + /// `endIndex`, `indices`, `count`, `isEmpty`, `index(before:)`, + /// `index(after:)`, `index(_:offsetBy:)`, `index(_:offsetBy:limitedBy:)`, and + /// `distance(from:to:)` by calling them with just about all possible input + /// combinations. + /// + /// - Parameters: + /// - collection: The collection to be validated. + /// - expectedCount: + /// + /// - Complexity: O(*n*^3) where *n* is the length of the collection if the + /// collection conforms to `RandomAccesCollection`, otherwise O(*n*^4). + func validate( + _ collection: C, + expectedCount: Int? = nil, + file: StaticString = #file, line: UInt = #line + ) { + let indicesIncludingEnd = self.indicesIncludingEnd(collection) let count = indicesIncludingEnd.count - 1 + let validator = Validator( + collection: collection, + count: count, + indicesIncludingEnd: indicesIncludingEnd, + file: file, line: line) + + validator.validateForward( + testRandomAccess: testRandomAccess, + expectedCount: expectedCount) + } +} + +extension IndexValidator where C: BidirectionalCollection { + func validate( + _ collection: C, expectedCount: Int? = nil, + file: StaticString = #file, line: UInt = #line + ) { + let indicesIncludingEnd = self.indicesIncludingEnd(collection) + let count = indicesIncludingEnd.count - 1 + + let validator = Validator( + collection: collection, + count: count, + indicesIncludingEnd: indicesIncludingEnd, + file: file, line: line) + + validator.validateForward( + testRandomAccess: testRandomAccess, + expectedCount: expectedCount) + validator.validateBackward(testRandomAccess: testRandomAccess) + } +} + +extension IndexValidator.Validator { + func validateForward(testRandomAccess: Bool, expectedCount: Int?) { + if let expectedCount = expectedCount { + XCTAssertEqual( + expectedCount, count, "Count mismatch", file: file, line: line) + } + XCTAssertEqual( - c.count, count, + collection.count, count, "Count mismatch", file: file, line: line) XCTAssertEqual( - c.isEmpty, count == 0, + collection.isEmpty, count == 0, "Emptiness mismatch", file: file, line: line) XCTAssertEqual( - c.startIndex, indicesIncludingEnd.first, + collection.startIndex, indicesIncludingEnd.first, "`startIndex` does not equal the first index", file: file, line: line) XCTAssertEqual( - c.endIndex, indicesIncludingEnd.last, + collection.endIndex, indicesIncludingEnd.last, "`endIndex` does not equal the last index", file: file, line: line) - // `index(after:)` - do { - var index = c.startIndex - - for (offset, expected) in indicesIncludingEnd.enumerated().dropFirst() { - c.formIndex(after: &index) - XCTAssertEqual( - index, expected, - """ - `startIndex` incremented \(offset) times does not equal index at \ - offset \(offset) - """, - file: file, line: line) - } - } + validateIndexAfter() + validateIndices() + validateIndexComparisons() - // `index(before:)` - do { - var index = c.endIndex - - for (offset, expected) in indicesIncludingEnd.enumerated().dropLast().reversed() { - c.formIndex(before: &index) - XCTAssertEqual( - index, expected, - """ - `endIndex` decremented \(count - offset) times does not equal index \ - at offset \(offset) - """, - file: file, line: line) - } + if testRandomAccess { + validateDistanceFromTo() + validateIndexOffsetBy() + validateIndexOffsetByLimitedBy() } + } + + func validateIndexAfter() { + var index = collection.startIndex - // `indices` - XCTAssertEqual(c.indices.count, count) - for (offset, index) in c.indices.enumerated() { + for (offset, expected) in indicesIncludingEnd.enumerated().dropFirst() { + collection.formIndex(after: &index) + XCTAssertEqual( + index, expected, + """ + `startIndex` incremented \(offset) times does not equal index at \ + offset \(offset) + """, + file: file, line: line) + } + } + + func validateIndices() { + XCTAssertEqual(collection.indices.count, count) + for (offset, index) in collection.indices.enumerated() { XCTAssertEqual( index, indicesIncludingEnd[offset], "Index mismatch at offset \(offset) in `indices`", file: file, line: line) } - - // index comparison + } + + func validateIndexComparisons() { for (offsetA, a) in indicesIncludingEnd.enumerated() { XCTAssertEqual( a, a, @@ -273,21 +342,14 @@ func validateIndexTraversals( file: file, line: line) } } - - // `index(_:offsetBy:)` and `distance(from:to:)` + } + + func validateDistanceFromTo() { for (startOffset, start) in indicesIncludingEnd.enumerated() { - for (endOffset, end) in indicesIncludingEnd.enumerated() { + for (endOffset, end) in indicesIncludingEnd.enumerated().dropFirst(startOffset) { let distance = endOffset - startOffset - XCTAssertEqual( - c.index(start, offsetBy: distance), end, - """ - Index at offset \(startOffset) offset by \(distance) does not equal \ - index at offset \(endOffset) - """, - file: file, line: line) - XCTAssertEqual( - c.distance(from: start, to: end), distance, + collection.distance(from: start, to: end), distance, """ Distance from index at offset \(startOffset) to index at offset \ \(endOffset) does not equal \(distance) @@ -295,18 +357,34 @@ func validateIndexTraversals( file: file, line: line) } } - - // `index(_:offsetBy:limitedBy:)` + } + + func validateIndexOffsetBy() { + for (startOffset, start) in indicesIncludingEnd.enumerated() { + for (endOffset, end) in indicesIncludingEnd.enumerated().dropFirst(startOffset) { + let distance = endOffset - startOffset + XCTAssertEqual( + collection.index(start, offsetBy: distance), end, + """ + Index at offset \(startOffset) offset by \(distance) does not \ + equal index at offset \(endOffset) + """, + file: file, line: line) + } + } + } + + func validateIndexOffsetByLimitedBy() { for (startOffset, start) in indicesIncludingEnd.enumerated() { for (limitOffset, limit) in indicesIncludingEnd.enumerated() { // verifies that the target index corresponding to each offset in // `range` can or cannot be reached from `start` using - // `chain.index(start, offsetBy: _, limitedBy: limit)`, depending on the - // value of `pastLimit` + // `chain.index(start, offsetBy: _, limitedBy: limit)`, depending on + // the value of `pastLimit` func checkTargetRange(_ range: ClosedRange, pastLimit: Bool) { for targetOffset in range { let distance = targetOffset - startOffset - let end = c.index(start, offsetBy: distance, limitedBy: limit) + let end = collection.index(start, offsetBy: distance, limitedBy: limit) if pastLimit { XCTAssertNil( @@ -329,7 +407,6 @@ func validateIndexTraversals( } } - // forward offsets if limit >= start { // the limit has an effect checkTargetRange(startOffset...limitOffset, pastLimit: false) @@ -338,8 +415,100 @@ func validateIndexTraversals( // the limit has no effect checkTargetRange(startOffset...count, pastLimit: false) } + } + } + } +} + +extension IndexValidator.Validator where C: BidirectionalCollection { + func validateBackward(testRandomAccess: Bool) { + validateIndexBefore() + + if testRandomAccess { + validateDistanceFromTo() + validateIndexOffsetBy() + validateIndexOffsetByLimitedBy() + } + } + + func validateIndexBefore() { + var index = collection.endIndex + + for (offset, expected) in indicesIncludingEnd.enumerated().dropLast().reversed() { + collection.formIndex(before: &index) + XCTAssertEqual( + index, expected, + """ + `endIndex` decremented \(count - offset) times does not equal index \ + at offset \(offset) + """, + file: file, line: line) + } + } + + func validateDistanceFromTo() { + for (startOffset, start) in indicesIncludingEnd.enumerated() { + for (endOffset, end) in indicesIncludingEnd.enumerated().prefix(startOffset) { + let distance = endOffset - startOffset + XCTAssertEqual( + collection.distance(from: start, to: end), distance, + """ + Distance from index at offset \(startOffset) to index at offset \ + \(endOffset) does not equal \(distance) + """, + file: file, line: line) + } + } + } + + func validateIndexOffsetBy() { + for (startOffset, start) in indicesIncludingEnd.enumerated() { + for (endOffset, end) in indicesIncludingEnd.enumerated().prefix(startOffset) { + let distance = endOffset - startOffset + XCTAssertEqual( + collection.index(start, offsetBy: distance), end, + """ + Index at offset \(startOffset) offset by \(distance) does not \ + equal index at offset \(endOffset) + """, + file: file, line: line) + } + } + } + + func validateIndexOffsetByLimitedBy() { + for (startOffset, start) in indicesIncludingEnd.enumerated() { + for (limitOffset, limit) in indicesIncludingEnd.enumerated() { + // verifies that the target index corresponding to each offset in + // `range` can or cannot be reached from `start` using + // `chain.index(start, offsetBy: _, limitedBy: limit)`, depending on + // the value of `pastLimit` + func checkTargetRange(_ range: ClosedRange, pastLimit: Bool) { + for targetOffset in range { + let distance = targetOffset - startOffset + let end = collection.index(start, offsetBy: distance, limitedBy: limit) + + if pastLimit { + XCTAssertNil( + end, + """ + Index at offset \(startOffset) offset by \(distance) limited \ + by index at offset \(limitOffset) does not equal `nil` + """, + file: file, line: line) + } else { + XCTAssertEqual( + end, indicesIncludingEnd[targetOffset], + """ + Index at offset \(startOffset) offset by \(distance) limited \ + by index at offset \(limitOffset) does not equal index at \ + offset \(targetOffset) + """, + file: file, line: line) + } + } + } - // backward offsets if limit <= start { // the limit has an effect checkTargetRange(limitOffset...startOffset, pastLimit: false) diff --git a/Tests/SwiftAlgorithmsTests/WindowsTests.swift b/Tests/SwiftAlgorithmsTests/WindowsTests.swift index 51ce285..92db185 100644 --- a/Tests/SwiftAlgorithmsTests/WindowsTests.swift +++ b/Tests/SwiftAlgorithmsTests/WindowsTests.swift @@ -12,8 +12,7 @@ import XCTest @testable import Algorithms -final class windowsTests: XCTestCase { - +final class WindowsTests: XCTestCase { func testWindowsOfString() { let s = "swift" let w = s.windows(ofCount: 2) @@ -87,22 +86,23 @@ final class windowsTests: XCTestCase { } func testWindowsIndexTraversals() { - validateIndexTraversals( - "".windows(ofCount: 1), - "a".windows(ofCount: 1), - "ab".windows(ofCount: 1), - "abc".windows(ofCount: 1), - "".windows(ofCount: 3), - "a".windows(ofCount: 3), - "abc".windows(ofCount: 3), - "abcdefgh".windows(ofCount: 3), - indices: { windows in + let validator = IndexValidator>( + indicesIncludingEnd: { windows in let endIndex = windows.base.endIndex let indices = windows.base.indices + [endIndex] - return zip(indices, indices.dropFirst(windows.size)) + return zip(indices, indices.dropFirst(windows.windowSize)) .map { .init(lowerBound: $0, upperBound: $1) } - + [.init(lowerBound: endIndex, upperBound: endIndex)] + + [.init(lowerBound: endIndex, upperBound: endIndex)] }) + + validator.validate("".windows(ofCount: 1), expectedCount: 0) + validator.validate("a".windows(ofCount: 1), expectedCount: 1) + validator.validate("ab".windows(ofCount: 1), expectedCount: 2) + validator.validate("abc".windows(ofCount: 1), expectedCount: 3) + validator.validate("".windows(ofCount: 3), expectedCount: 0) + validator.validate("a".windows(ofCount: 3), expectedCount: 0) + validator.validate("abc".windows(ofCount: 3), expectedCount: 1) + validator.validate("abcdefgh".windows(ofCount: 3), expectedCount: 6) } func testWindowsLazy() {