From 88be07a691bd37d87e1bb4666bb0f935abe90986 Mon Sep 17 00:00:00 2001 From: Tim Vermeulen Date: Wed, 18 Aug 2021 19:52:34 +0200 Subject: [PATCH] Rename types to include a Sequence or Collection suffix, and clean up some guides --- Guides/AdjacentPairs.md | 33 ++++++---- Guides/Chain.md | 8 +-- Guides/Chunked.md | 76 ++++++++++++----------- Guides/Combinations.md | 21 ++++--- Guides/Cycle.md | 18 +++--- Guides/Indexed.md | 8 +-- Guides/Intersperse.md | 12 ++-- Guides/LazySplit.md | 45 +++++++------- Guides/MinMax.md | 44 +++++++++++--- Guides/Permutations.md | 21 ++++--- Guides/Product.md | 14 ++--- Guides/RandomSampling.md | 4 +- Guides/Reductions.md | 51 ++++++++-------- Guides/Stride.md | 19 +++--- Guides/Suffix.md | 28 ++++----- Guides/Trim.md | 88 ++++++++++++++++----------- Guides/Unique.md | 23 ++++--- Guides/Windows.md | 18 +++--- Sources/Algorithms/Chain.swift | 27 ++++---- Sources/Algorithms/Chunked.swift | 67 ++++++++++---------- Sources/Algorithms/Combinations.swift | 16 ++--- Sources/Algorithms/Cycle.swift | 40 ++++++------ Sources/Algorithms/Indexed.swift | 16 ++--- Sources/Algorithms/Intersperse.swift | 38 ++++++------ Sources/Algorithms/Joined.swift | 16 ++--- Sources/Algorithms/LazySplit.swift | 30 ++++----- Sources/Algorithms/Permutations.swift | 34 +++++------ Sources/Algorithms/Product.swift | 18 +++--- Sources/Algorithms/Reductions.swift | 36 +++++------ Sources/Algorithms/Stride.swift | 26 ++++---- Sources/Algorithms/Unique.swift | 15 ++--- Sources/Algorithms/Windows.swift | 18 +++--- 32 files changed, 499 insertions(+), 429 deletions(-) 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..beaaae8 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()) @@ -66,28 +66,28 @@ versions that return a lazy wrapper added to `LazyCollectionProtocol`. ```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)] +} - extension LazyCollectionProtocol { - public func chunked( - by belongInSameGroup: @escaping (Element, Element) -> Bool - ) -> ChunkedBy +extension LazyCollectionProtocol { + 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` and `ChunkedOnCollection` types are bidirectional when +the wrapped collection is bidirectional. ### Complexity @@ -95,12 +95,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/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..4fc5241 100644 --- a/Guides/Indexed.md +++ b/Guides/Indexed.md @@ -25,11 +25,11 @@ The `indexed` method returns an `Indexed` 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` +and `LazyCollectionProtocol` when the base type conforms. diff --git a/Guides/Intersperse.md b/Guides/Intersperse.md index ee5f91d..41f866c 100644 --- a/Guides/Intersperse.md +++ b/Guides/Intersperse.md @@ -25,15 +25,15 @@ 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 -protocols. +The new `InterspersedSequence` type represents the sequence when the separator +is inserted between each element. `InterspersedSequence` conforms to +`Collection`, `BidirectionalCollection`, `RandomAccessCollection`, +`LazySequenceProtocol` and `LazyCollectionProtocol` when the base sequence +conforms to those respective protocols. ### Complexity diff --git a/Guides/LazySplit.md b/Guides/LazySplit.md index 08bb1b7..a812756 100644 --- a/Guides/LazySplit.md +++ b/Guides/LazySplit.md @@ -15,9 +15,9 @@ collection without allocating additional storage on the heap. // 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 } + whereSeparator: { $0 % 3 == 0 || $0 % 5 == 0 } ) { - print(subsequence) + print(subsequence) } /* Prints: [1, 2] @@ -31,7 +31,7 @@ for subsequence in numbers.lazy.split( // Splitting a lazy collection. let line = "BLANCHE: I don't want realism. I want magic!" for subsequence in line.lazy.split(separator: " ") { - print(subsequence) + print(subsequence) } /* Prints BLANCHE: @@ -52,29 +52,28 @@ magic! `split(separator:maxSplits:omittingEmptySubsequences:)`. The `LazySequence` versions of those methods return an instance of -`LazySplitSequence`. The `LazyCollection` versions return an instance of -`LazySplitCollection`. +`SplitSequence`. The `LazyCollection` versions return an instance of +`SplitCollection`. -`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. +`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. -`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. +`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 `LazySplitSequence` instance is O(_n_) in time and space, -since each subsequence returned is a newly-allocated array. +Iterating a `SplitSequence` 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). +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/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..0539e96 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,7 +120,7 @@ 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 +array at every index advancement. The `PermutationsSequence` type conforms to `LazySequenceProtocol` when its base type conforms. ### Complexity @@ -128,9 +129,9 @@ Calling `permutations()` is an O(1) operation. Creating the iterator for a `Permutations` instance and each call to `Permutations.Iterator.next()` is an O(_n_) operation. -Calling `uniquePermutations()` is an O(_n_) operation, because it preprocesses the -collection to find duplicate elements. Creating the iterator for and each call to -`next()` is also an O(_n_) operation. +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..4a2a1d3 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 `Zip2` 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/Stride.md b/Guides/Stride.md index a309f25..2914bc8 100644 --- a/Guides/Stride.md +++ b/Guides/Stride.md @@ -19,25 +19,25 @@ 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: +`StridingSequence` type: ```swift extension Sequence { - public func striding(by step: Int) -> Stride + public func striding(by step: Int) -> StridingSequence } ``` -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. +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. ```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 +52,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..c7c09d7 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) -> WindowsCollection } ``` -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 +The resulting `WindowsCollection` type is a collection, with conditional +conformance to the `BidirectionalCollection`, `RandomAccessCollection`, and `LazyCollectionProtocol` 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/Sources/Algorithms/Chain.swift b/Sources/Algorithms/Chain.swift index 57dee3a..d8920d4 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,7 +28,7 @@ public struct Chain2 } } -extension Chain2: Sequence { +extension Chain2Sequence: Sequence { /// The iterator for a `Chain2` sequence. public struct Iterator: IteratorProtocol { @usableFromInline @@ -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,7 +55,7 @@ extension Chain2: Sequence { } } -extension Chain2: Collection where Base1: Collection, Base2: Collection { +extension Chain2Sequence: Collection where Base1: Collection, Base2: Collection { /// A position in a `Chain2` collection. public struct Index: Comparable { // The internal index representation, which can either be an index of the @@ -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,23 @@ extension Chain2: RandomAccessCollection /// /// - Complexity: O(1) @inlinable -public func chain(_ s1: S1, _ s2: S2) -> Chain2 { - Chain2(base1: s1, base2: s2) +public func chain(_ s1: S1, _ s2: S2) -> Chain2Sequence { + Chain2Sequence(base1: s1, base2: s2) } // MARK: - Deprecations -@available(*, deprecated, renamed: "Chain2") -public typealias Chain = Chain2 +@available(*, deprecated, renamed: "Chain2Sequence") +public typealias Chain = Chain2Sequence + +@available(*, deprecated, renamed: "Chain2Sequence") +public typealias Chain2 = Chain2Sequence extension Sequence { @available(*, deprecated, message: "Use the chain(_:_:) function, instead.") - public func chained(with other: S) -> Chain2 + public func chained(with other: S) -> Chain2Sequence where Element == S.Element { - Chain2(base1: self, base2: other) + Chain2Sequence(base1: self, base2: other) } } diff --git a/Sources/Algorithms/Chunked.swift b/Sources/Algorithms/Chunked.swift index 883ecf3..c9af28b 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 @@ -47,7 +47,7 @@ public struct ChunkedBy { } } -extension ChunkedBy: LazyCollectionProtocol { +extension ChunkedByCollection: LazyCollectionProtocol { /// A position in a chunked collection. public struct Index: Comparable { /// The range corresponding to the chunk at this position. @@ -112,9 +112,9 @@ extension ChunkedBy: LazyCollectionProtocol { } } -extension ChunkedBy.Index: Hashable where Base.Index: Hashable {} +extension ChunkedByCollection.Index: Hashable where Base.Index: Hashable {} -extension ChunkedBy: BidirectionalCollection +extension ChunkedByCollection: BidirectionalCollection where Base: BidirectionalCollection { /// Returns the index in the base collection of the start of the chunk ending @@ -139,19 +139,22 @@ extension ChunkedBy: BidirectionalCollection } } -@available(*, deprecated, renamed: "ChunkedBy") -public typealias LazyChunked = ChunkedBy +@available(*, deprecated, renamed: "ChunkedByCollection") +public typealias LazyChunked = ChunkedByCollection -@available(*, deprecated, renamed: "ChunkedBy") -public typealias Chunked = ChunkedBy +@available(*, deprecated, renamed: "ChunkedByCollection") +public typealias Chunked = ChunkedByCollection + +@available(*, deprecated, renamed: "ChunkedByCollection") +public typealias ChunkedBy = ChunkedByCollection /// 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( @@ -159,12 +162,12 @@ public struct ChunkedOn { projection: @escaping (Base.Element) -> Subject, belongInSameGroup: @escaping (Subject, Subject) -> Bool ) { - self.chunked = ChunkedBy(base: base, projection: projection, belongInSameGroup: belongInSameGroup) + self.chunked = ChunkedByCollection(base: base, projection: projection, belongInSameGroup: belongInSameGroup) } } -extension ChunkedOn: LazyCollectionProtocol { - public typealias Index = ChunkedBy.Index +extension ChunkedOnCollection: LazyCollectionProtocol { + public typealias Index = ChunkedByCollection.Index @inlinable public var startIndex: Index { @@ -189,7 +192,7 @@ extension ChunkedOn: LazyCollectionProtocol { } } -extension ChunkedOn: BidirectionalCollection where Base: BidirectionalCollection { +extension ChunkedOnCollection: BidirectionalCollection where Base: BidirectionalCollection { public func index(before i: Index) -> Index { chunked.index(before: i) } @@ -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) @@ -221,8 +224,8 @@ extension LazyCollectionProtocol { @inlinable public func chunked( on projection: @escaping (Element) -> Subject - ) -> ChunkedOn { - ChunkedOn( + ) -> ChunkedOnCollection { + ChunkedOnCollection( base: elements, projection: projection, belongInSameGroup: ==) @@ -307,7 +310,7 @@ extension Collection { /// * `c.chunks(ofCount: 3)` does not create new storage /// * `c.chunks(ofCount: 3).map(f)` maps eagerly and returns a new array /// * `c.lazy.chunks(ofCount: 3).map(f)` maps lazily and returns a `LazyMapCollection` -public struct ChunkedByCount { +public struct ChunksOfCountCollection { public typealias Element = Base.SubSequence @@ -338,7 +341,7 @@ public struct ChunkedByCount { } } -extension ChunkedByCount: Collection { +extension ChunksOfCountCollection: Collection { public struct Index { @usableFromInline internal let baseRange: Range @@ -377,21 +380,21 @@ 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 @@ -414,7 +417,7 @@ where Base: RandomAccessCollection { } } -extension ChunkedByCount { +extension ChunksOfCountCollection { @inlinable public func distance(from start: Index, to end: Index) -> Int { let distance = @@ -572,16 +575,16 @@ 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 where Base: LazySequenceProtocol {} -extension ChunkedByCount: LazyCollectionProtocol +extension ChunksOfCountCollection: LazyCollectionProtocol where Base: LazyCollectionProtocol {} diff --git a/Sources/Algorithms/Combinations.swift b/Sources/Algorithms/Combinations.swift index 7b4a421..5034f31 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 @@ -76,7 +76,7 @@ public struct Combinations { } } -extension Combinations: Sequence { +extension CombinationsSequence: Sequence { /// The iterator for a `Combinations` instance. public struct Iterator: IteratorProtocol { @usableFromInline @@ -99,7 +99,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)) @@ -180,7 +180,7 @@ extension Combinations: Sequence { } } -extension Combinations: LazySequenceProtocol where Base: LazySequenceProtocol {} +extension CombinationsSequence: LazySequenceProtocol where Base: LazySequenceProtocol {} //===----------------------------------------------------------------------===// // combinations(ofCount:) @@ -251,8 +251,8 @@ extension Collection { @inlinable public func combinations( ofCount kRange: R - ) -> Combinations where R.Bound == Int { - return Combinations(self, kRange: kRange) + ) -> CombinationsSequence where R.Bound == Int { + return CombinationsSequence(self, kRange: kRange) } /// Returns a collection of combinations of this collection's elements, with @@ -285,8 +285,8 @@ extension Collection { /// is the number of elements in the base collection, since `Combinations` /// 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/Cycle.swift b/Sources/Algorithms/Cycle.swift index fc6671d..a92b4e4 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,7 +21,7 @@ public struct Cycle { } } -extension Cycle: Sequence { +extension CycledSequence: Sequence { /// The iterator for a `Cycle` sequence. public struct Iterator: IteratorProtocol { @usableFromInline @@ -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 } @@ -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/Indexed.swift b/Sources/Algorithms/Indexed.swift index d1fdd37..fcf0ef9 100644 --- a/Sources/Algorithms/Indexed.swift +++ b/Sources/Algorithms/Indexed.swift @@ -11,7 +11,7 @@ /// A collection wrapper that iterates over the indices and elements of a /// collection together. -public struct Indexed { +public struct IndexedCollection { /// The element type for an `Indexed` collection. public typealias Element = (index: Base.Index, element: Base.Element) @@ -25,7 +25,7 @@ public struct Indexed { } } -extension Indexed: Collection { +extension IndexedCollection: Collection { @inlinable public var startIndex: Base.Index { base.startIndex @@ -62,16 +62,16 @@ extension Indexed: Collection { } } -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 where Base: LazySequenceProtocol {} +extension IndexedCollection: LazyCollectionProtocol where Base: LazyCollectionProtocol {} //===----------------------------------------------------------------------===// // indexed() @@ -94,7 +94,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..b213586 100644 --- a/Sources/Algorithms/Intersperse.swift +++ b/Sources/Algorithms/Intersperse.swift @@ -15,7 +15,7 @@ /// A sequence that presents the elements of a base sequence of elements /// with a separator between each of those elements. -public struct Intersperse { +public struct InterspersedSequence { @usableFromInline internal let base: Base @@ -29,7 +29,7 @@ public struct Intersperse { } } -extension Intersperse: Sequence { +extension InterspersedSequence: Sequence { /// The iterator for an `Intersperse` sequence. public struct Iterator: IteratorProtocol { @usableFromInline @@ -76,12 +76,12 @@ 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 { +extension InterspersedSequence: Collection where Base: Collection { /// A position in an `Intersperse` collection. public struct Index: Comparable { @usableFromInline @@ -256,7 +256,7 @@ extension Intersperse: Collection where Base: Collection { } } -extension Intersperse: BidirectionalCollection +extension InterspersedSequence: BidirectionalCollection where Base: BidirectionalCollection { @inlinable @@ -271,13 +271,13 @@ extension Intersperse: BidirectionalCollection } } -extension Intersperse: RandomAccessCollection +extension InterspersedSequence: RandomAccessCollection where Base: RandomAccessCollection {} -extension Intersperse: LazySequenceProtocol +extension InterspersedSequence: LazySequenceProtocol where Base: LazySequenceProtocol {} -extension Intersperse: LazyCollectionProtocol +extension InterspersedSequence: LazyCollectionProtocol where Base: LazyCollectionProtocol {} //===----------------------------------------------------------------------===// @@ -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,7 +300,7 @@ internal struct InterspersedMap { internal let separator: (Base.Element, Base.Element) -> Result } -extension InterspersedMap: Sequence { +extension InterspersedMapSequence: Sequence { @usableFromInline internal struct Iterator: IteratorProtocol { @usableFromInline @@ -360,7 +360,7 @@ extension InterspersedMap: Sequence { } } -extension InterspersedMap: Collection where Base: Collection { +extension InterspersedMapSequence: Collection where Base: Collection { @usableFromInline internal struct Index: Comparable { @usableFromInline @@ -561,7 +561,7 @@ extension InterspersedMap: Collection where Base: Collection { } } -extension InterspersedMap: BidirectionalCollection +extension InterspersedMapSequence: BidirectionalCollection where Base: BidirectionalCollection { @inlinable @@ -577,12 +577,12 @@ extension InterspersedMap: BidirectionalCollection } } -extension InterspersedMap.Index.Representation: Hashable +extension InterspersedMapSequence.Index.Representation: Hashable where Base.Index: Hashable {} -extension InterspersedMap: LazySequenceProtocol +extension InterspersedMapSequence: LazySequenceProtocol where Base: LazySequenceProtocol {} -extension InterspersedMap: LazyCollectionProtocol +extension InterspersedMapSequence: LazyCollectionProtocol where Base: LazyCollectionProtocol {} //===----------------------------------------------------------------------===// @@ -620,8 +620,8 @@ 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) } } @@ -647,7 +647,7 @@ 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: self, transform: transform, separator: separator) } } diff --git a/Sources/Algorithms/Joined.swift b/Sources/Algorithms/Joined.swift index d630a2d..9b02cec 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, EitherSequence>> @usableFromInline internal let inner: Inner @@ -124,8 +124,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 @@ -228,8 +228,8 @@ public struct JoinedByClosureCollection where Base.Element: Collection, Base.Element.Element == Separator.Element { @usableFromInline - internal typealias Inner = FlattenCollection< - InterspersedMap, EitherSequence>> + internal typealias Inner = FlattenCollection, EitherSequence>> @usableFromInline internal let inner: Inner diff --git a/Sources/Algorithms/LazySplit.swift b/Sources/Algorithms/LazySplit.swift index 9241e63..bc6bc39 100644 --- a/Sources/Algorithms/LazySplit.swift +++ b/Sources/Algorithms/LazySplit.swift @@ -21,7 +21,7 @@ /// x.split(separator:maxSplits:omittingEmptySubsequences) /// /// where `x` conforms to `LazySequenceProtocol`. -public struct LazySplitSequence { +public struct SplitSequence { @usableFromInline internal let base: Base @@ -48,7 +48,7 @@ public struct LazySplitSequence { } } -extension LazySplitSequence { +extension SplitSequence { public struct Iterator { public typealias Element = [Base.Element] @@ -87,7 +87,7 @@ extension LazySplitSequence { } } -extension LazySplitSequence.Iterator: IteratorProtocol { +extension SplitSequence.Iterator: IteratorProtocol { @inlinable public mutating func next() -> Element? { var currentElement = base.next() @@ -128,7 +128,7 @@ extension LazySplitSequence.Iterator: IteratorProtocol { } } -extension LazySplitSequence: LazySequenceProtocol { +extension SplitSequence: LazySequenceProtocol { @inlinable public func makeIterator() -> Iterator { return Iterator( @@ -230,10 +230,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 +320,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, @@ -344,7 +344,7 @@ extension LazySequenceProtocol where Element: Equatable { /// x.split(separator:maxSplits:omittingEmptySubsequences) /// /// where `x` conforms to `LazyCollectionProtocol`. -public struct LazySplitCollection { +public struct SplitCollection { @usableFromInline internal let base: Base @@ -398,7 +398,7 @@ public struct LazySplitCollection { } } -extension LazySplitCollection: LazyCollectionProtocol { +extension SplitCollection: LazyCollectionProtocol { /// Position of a subsequence in a split collection. public struct Index: Comparable { /// The range corresponding to the subsequence at this position. @@ -547,7 +547,7 @@ extension LazySplitCollection: LazyCollectionProtocol { } } -extension LazySplitCollection.Index: Hashable { +extension SplitCollection.Index: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(sequenceLength) } @@ -641,10 +641,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, @@ -737,10 +737,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/Permutations.swift b/Sources/Algorithms/Permutations.swift index 29e6459..84507f9 100644 --- a/Sources/Algorithms/Permutations.swift +++ b/Sources/Algorithms/Permutations.swift @@ -76,7 +76,7 @@ extension MutableCollection //===----------------------------------------------------------------------===// /// A sequence of all the permutations of a collection's elements. -public struct Permutations { +public struct PermutationsSequence { /// The base collection to iterate over for permutations. @usableFromInline internal let base: Base @@ -134,7 +134,7 @@ public struct Permutations { } } -extension Permutations: Sequence { +extension PermutationsSequence: Sequence { /// The iterator for a `Permutations` instance. public struct Iterator: IteratorProtocol { @usableFromInline @@ -160,7 +160,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 +259,7 @@ extension Permutations: Sequence { } } -extension Permutations: LazySequenceProtocol where Base: LazySequenceProtocol {} +extension PermutationsSequence: LazySequenceProtocol where Base: LazySequenceProtocol {} //===----------------------------------------------------------------------===// // permutations(ofCount:) @@ -325,8 +325,8 @@ extension Collection { @inlinable public func permutations( ofCount kRange: R - ) -> Permutations where R.Bound == Int { - return Permutations(self, kRange: kRange) + ) -> PermutationsSequence where R.Bound == Int { + return PermutationsSequence(self, kRange: kRange) } /// Returns a collection of the permutations of this collection of the @@ -379,11 +379,11 @@ extension Collection { /// is the number of elements in the base collection, since `Permutations` /// accesses the `count` of the base collection. @inlinable - public func permutations(ofCount k: Int? = nil) -> Permutations { + 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) } } @@ -396,7 +396,7 @@ extension Collection { /// /// To create a `UniquePermutations` 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 +408,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,7 +440,7 @@ extension UniquePermutations where Base.Element: Hashable { } } -extension UniquePermutations: Sequence { +extension UniquePermutationsSequence: Sequence { /// The iterator for a `UniquePermutations` instance. public struct Iterator: IteratorProtocol { @usableFromInline @@ -496,7 +496,7 @@ 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 +537,11 @@ 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 { + 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 +574,9 @@ 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 + public func uniquePermutations(ofCount kRange: R) -> UniquePermutationsSequence where R.Bound == Int { - UniquePermutations(self, kRange) + UniquePermutationsSequence(self, kRange) } } diff --git a/Sources/Algorithms/Product.swift b/Sources/Algorithms/Product.swift index dd6b8b0..bbcdf29 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,7 +26,7 @@ public struct Product2 { } } -extension Product2: Sequence { +extension Product2Sequence: Sequence { public typealias Element = (Base1.Element, Base2.Element) /// The iterator for a `Product2` sequence. @@ -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() @@ -88,7 +88,7 @@ extension Product2: Sequence { } } -extension Product2: Collection where Base1: Collection { +extension Product2Sequence: Collection where Base1: Collection { /// The index type for a `Product2` collection. public struct Index: Comparable { @usableFromInline @@ -419,7 +419,7 @@ extension Product2: Collection where Base1: Collection { } } -extension Product2: BidirectionalCollection +extension Product2Sequence: BidirectionalCollection where Base1: BidirectionalCollection, Base2: BidirectionalCollection { @inlinable @@ -436,10 +436,10 @@ 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 +481,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 { + return Product2Sequence(s1, s2) } diff --git a/Sources/Algorithms/Reductions.swift b/Sources/Algorithms/Reductions.swift index c0c39a3..b8917df 100644 --- a/Sources/Algorithms/Reductions.swift +++ b/Sources/Algorithms/Reductions.swift @@ -38,7 +38,7 @@ extension LazySequenceProtocol { public func reductions( _ initial: Result, _ transform: @escaping (Result, Element) -> Result - ) -> ExclusiveReductions { + ) -> ExclusiveReductionsSequence { return reductions(into: initial) { result, element in result = transform(result, element) } @@ -69,8 +69,8 @@ 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: self, initial: initial, transform: transform) } } @@ -176,7 +176,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 +198,7 @@ public struct ExclusiveReductions { } } -extension ExclusiveReductions: Sequence { +extension ExclusiveReductionsSequence: Sequence { public struct Iterator: IteratorProtocol { @usableFromInline internal var iterator: Base.Iterator @@ -240,7 +240,7 @@ extension ExclusiveReductions: Sequence { } } -extension ExclusiveReductions: Collection where Base: Collection { +extension ExclusiveReductionsSequence: Collection where Base: Collection { public struct Index: Comparable { @usableFromInline internal let representation: ReductionsIndexRepresentation @@ -316,10 +316,10 @@ extension ExclusiveReductions: Collection where Base: Collection { } } -extension ExclusiveReductions: LazySequenceProtocol +extension ExclusiveReductionsSequence: LazySequenceProtocol where Base: LazySequenceProtocol {} -extension ExclusiveReductions: LazyCollectionProtocol +extension ExclusiveReductionsSequence: LazyCollectionProtocol where Base: LazyCollectionProtocol {} // MARK: - Inclusive Reductions @@ -348,8 +348,8 @@ extension LazySequenceProtocol { @inlinable public func reductions( _ transform: @escaping (Element, Element) -> Element - ) -> InclusiveReductions { - InclusiveReductions(base: self, transform: transform) + ) -> InclusiveReductionsSequence { + InclusiveReductionsSequence(base: self, transform: transform) } } @@ -400,7 +400,7 @@ extension Sequence { } } -public struct InclusiveReductions { +public struct InclusiveReductionsSequence { @usableFromInline internal let base: Base @@ -417,7 +417,7 @@ public struct InclusiveReductions { } } -extension InclusiveReductions: Sequence { +extension InclusiveReductionsSequence: Sequence { public struct Iterator: IteratorProtocol { @usableFromInline internal var iterator: Base.Iterator @@ -458,7 +458,7 @@ extension InclusiveReductions: Sequence { } } -extension InclusiveReductions: Collection where Base: Collection { +extension InclusiveReductionsSequence: Collection where Base: Collection { public struct Index: Comparable { @usableFromInline internal let representation: ReductionsIndexRepresentation @@ -536,10 +536,10 @@ extension InclusiveReductions: Collection where Base: Collection { } } -extension InclusiveReductions: LazySequenceProtocol +extension InclusiveReductionsSequence: LazySequenceProtocol where Base: LazySequenceProtocol {} -extension InclusiveReductions: LazyCollectionProtocol +extension InclusiveReductionsSequence: LazyCollectionProtocol where Base: LazyCollectionProtocol {} // MARK: - ReductionsIndexRepresentation @@ -585,7 +585,7 @@ extension LazySequenceProtocol { public func scan( _ initial: Result, _ transform: @escaping (Result, Element) -> Result - ) -> ExclusiveReductions { + ) -> ExclusiveReductionsSequence { reductions(initial, transform) } @@ -594,7 +594,7 @@ extension LazySequenceProtocol { public func scan( into initial: Result, _ transform: @escaping (inout Result, Element) -> Void - ) -> ExclusiveReductions { + ) -> ExclusiveReductionsSequence { reductions(into: initial, transform) } } @@ -626,7 +626,7 @@ extension LazySequenceProtocol { @inlinable public func scan( _ transform: @escaping (Element, Element) -> Element - ) -> InclusiveReductions { + ) -> InclusiveReductionsSequence { reductions(transform) } } diff --git a/Sources/Algorithms/Stride.swift b/Sources/Algorithms/Stride.swift index ba1f0d3..e1223d1 100644 --- a/Sources/Algorithms/Stride.swift +++ b/Sources/Algorithms/Stride.swift @@ -27,8 +27,8 @@ extension Sequence { /// - 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) } } @@ -47,13 +47,13 @@ extension Collection { /// - 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: Sequence { @usableFromInline internal let base: Base @@ -69,7 +69,7 @@ public struct StrideSequence: Sequence { } } -extension StrideSequence { +extension StridingSequence { /// An iterator over a `Stride` sequence. public struct Iterator: IteratorProtocol { @@ -107,7 +107,7 @@ extension StrideSequence { } } -extension StrideSequence { +extension StridingSequence { @inlinable public func striding(by step: Int) -> Self { Self(base: base, stride: stride * step) @@ -115,7 +115,7 @@ extension StrideSequence { } /// A wrapper that strides over a base collection. -public struct StrideCollection { +public struct StridingCollection { @usableFromInline internal let base: Base @@ -130,14 +130,14 @@ public struct StrideCollection { } } -extension StrideCollection { +extension StridingCollection { @inlinable public func striding(by step: Int) -> Self { Self(base: base, stride: stride * step) } } -extension StrideCollection: Collection { +extension StridingCollection: Collection { /// A position in a `Stride` collection. public struct Index: Comparable { @@ -264,7 +264,7 @@ extension StrideCollection: Collection { } } -extension StrideCollection: BidirectionalCollection +extension StridingCollection: BidirectionalCollection where Base: RandomAccessCollection { @inlinable @@ -274,5 +274,5 @@ extension StrideCollection: BidirectionalCollection } } -extension StrideCollection: RandomAccessCollection where Base: RandomAccessCollection {} -extension StrideCollection.Index: Hashable where Base.Index: Hashable {} +extension StridingCollection: RandomAccessCollection where Base: RandomAccessCollection {} +extension StridingCollection.Index: Hashable where Base.Index: Hashable {} diff --git a/Sources/Algorithms/Unique.swift b/Sources/Algorithms/Unique.swift index cb72289..63056ff 100644 --- a/Sources/Algorithms/Unique.swift +++ b/Sources/Algorithms/Unique.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// /// A sequence wrapper that leaves out duplicate elements of a base sequence. -public struct Uniqued { +public struct UniquedSequence { /// The base collection. @usableFromInline internal let base: Base @@ -26,7 +26,7 @@ public struct Uniqued { } } -extension Uniqued: Sequence { +extension UniquedSequence: Sequence { /// The iterator for a `Uniqued` sequence. public struct Iterator: IteratorProtocol { @usableFromInline @@ -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 }) } } @@ -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..5d081a0 100644 --- a/Sources/Algorithms/Windows.swift +++ b/Sources/Algorithms/Windows.swift @@ -39,14 +39,14 @@ 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) -> WindowsCollection { + WindowsCollection(base: self, size: count) } } /// A collection wrapper that presents a sliding window over the elements of /// a collection. -public struct Windows { +public struct WindowsCollection { @usableFromInline internal let base: Base @@ -66,7 +66,7 @@ public struct Windows { } } -extension Windows: Collection { +extension WindowsCollection: Collection { /// A position in a `Windows` collection. public struct Index: Comparable { @usableFromInline @@ -329,7 +329,7 @@ extension Windows: Collection { } } -extension Windows: BidirectionalCollection where Base: BidirectionalCollection { +extension WindowsCollection: BidirectionalCollection where Base: BidirectionalCollection { @inlinable public func index(before index: Index) -> Index { precondition(index > startIndex, "Incrementing past start index") @@ -347,7 +347,7 @@ 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 WindowsCollection: LazySequenceProtocol where Base: LazySequenceProtocol {} +extension WindowsCollection: LazyCollectionProtocol where Base: LazyCollectionProtocol {} +extension WindowsCollection: RandomAccessCollection where Base: RandomAccessCollection {} +extension WindowsCollection.Index: Hashable where Base.Index: Hashable {}