diff --git a/Guides/Chunked.md b/Guides/Chunked.md index beaaae8..4b230c0 100644 --- a/Guides/Chunked.md +++ b/Guides/Chunked.md @@ -61,8 +61,9 @@ c.elementsEqual(c.chunked(...).joined()) ## Detailed Design -The two methods are added as extension to `Collection`, with two matching -versions that return a lazy wrapper added to `LazyCollectionProtocol`. +The three methods are added as extension to `Collection`. `chunked(by:)` and +`chunked(on:)` are eager by default, both with a matching version that return a +lazy wrapper added to `LazySequenceProtocol`. ```swift extension Collection { @@ -73,9 +74,11 @@ extension Collection { public func chunked( on projection: (Element) -> Subject ) -> [(Subject, SubSequence)] + + public func chunks(ofCount count: Int) -> ChunksOfCountCollection } -extension LazyCollectionProtocol { +extension LazySequenceProtocol where Self: Collection, Elements: Collection { public func chunked( by belongInSameGroup: @escaping (Element, Element) -> Bool ) -> ChunkedByCollection @@ -86,8 +89,10 @@ extension LazyCollectionProtocol { } ``` -The `ChunkedByCollection` and `ChunkedOnCollection` types are bidirectional when -the wrapped collection is bidirectional. +The `ChunkedByCollection`, `ChunkedOnCollection`, and `ChunksOfCountCollection` +types are bidirectional when the wrapped collection is bidirectional. +`ChunksOfCountCollection` also conforms to `LazySequenceProtocol` when the base +collection conforms. ### Complexity diff --git a/Guides/Compacted.md b/Guides/Compacted.md index 9e844ec..0398a3f 100644 --- a/Guides/Compacted.md +++ b/Guides/Compacted.md @@ -37,8 +37,9 @@ extension Collection { The `Sequence` version of `compacted()` returns a `CompactedSequence` type, while the `Collection` version returns `CompactedCollection`. The collection -has conditional conformance to `BidirectionalCollection` and -`LazyCollectionProtocol` when the base collection conforms. +has conditional conformance to `BidirectionalCollection` when the base +collection conforms, and both have conditional conformance to +`LazySequenceProtocol` when the base collection conforms. ### Naming diff --git a/Guides/Indexed.md b/Guides/Indexed.md index 4fc5241..09d647c 100644 --- a/Guides/Indexed.md +++ b/Guides/Indexed.md @@ -21,7 +21,7 @@ for (i, n) in numbers.indexed() { ## Detailed Design -The `indexed` method returns an `Indexed` type: +The `indexed` method returns an `IndexedCollection` type: ```swift extension Collection { @@ -31,5 +31,5 @@ extension Collection { `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. +when the base type conforms. diff --git a/Guides/Intersperse.md b/Guides/Intersperse.md index 41f866c..00c2b28 100644 --- a/Guides/Intersperse.md +++ b/Guides/Intersperse.md @@ -31,9 +31,9 @@ extension Sequence { 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. +`Collection`, `BidirectionalCollection`, `RandomAccessCollection` and +`LazySequenceProtocol` when the base sequence conforms to those respective +protocols. ### Complexity diff --git a/Guides/Joined.md b/Guides/Joined.md index 9b7a629..9b33126 100644 --- a/Guides/Joined.md +++ b/Guides/Joined.md @@ -70,8 +70,7 @@ Note that the sequence separator of the closure-less version defined on general be iterated over multiple times. The closure-based versions also have lazy variants that are defined on both -`LazySequenceProtocol` and `LazyCollectionProtocol` for the same reason as -explained above: +lazy sequences and collections for the same reason as explained above: ```swift extension LazySequenceProtocol where Element: Sequence { @@ -84,7 +83,7 @@ extension LazySequenceProtocol where Element: Sequence { ) -> JoinedByClosureSequence } -extension LazyCollectionProtocol where Element: Collection { +extension LazySequenceProtocol where Self: Collection, Element: Collection { public func joined( by separator: @escaping (Element, Element) -> Element.Element ) -> JoinedByClosureCollection> @@ -98,5 +97,4 @@ extension LazyCollectionProtocol where Element: Collection { `JoinedBySequence`, `JoinedByClosureSequence`, `JoinedByCollection`, and `JoinedByClosureCollection` conform to `LazySequenceProtocol` when the base sequence conforms. `JoinedByCollection` and `JoinedByClosureCollection` also -conform to `LazyCollectionProtocol` and `BidirectionalCollection` when the base -collection conforms. +conform to `BidirectionalCollection` when the base collection conforms. diff --git a/Guides/Permutations.md b/Guides/Permutations.md index 0539e96..6080a0c 100644 --- a/Guides/Permutations.md +++ b/Guides/Permutations.md @@ -120,14 +120,15 @@ 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 `PermutationsSequence` type -conforms to `LazySequenceProtocol` when its base type conforms. +array at every index advancement. The `PermutationsSequence` and +`UniquePermutationsSequence` types conforms to `LazySequenceProtocol` when their +base type conforms. ### Complexity Calling `permutations()` is an O(1) operation. Creating the iterator for a -`Permutations` instance and each call to `Permutations.Iterator.next()` is an -O(_n_) operation. +`PermutationsSequence` instance and each call to +`PermutationsSequence.Iterator.next()` is an O(_n_) operation. Calling `uniquePermutations()` is an O(_n_) operation, because it preprocesses the collection to find duplicate elements. Creating the iterator for and each diff --git a/Guides/Product.md b/Guides/Product.md index 4a2a1d3..6271107 100644 --- a/Guides/Product.md +++ b/Guides/Product.md @@ -43,8 +43,8 @@ collection, and a random-access collection when both base collections have those conformances. 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. +etc.) at this time to match the standard library's `Zip2Sequence` type. Users +can compose multiple calls to `product` if they would like higher arities. ### Complexity diff --git a/Guides/LazySplit.md b/Guides/Split.md similarity index 96% rename from Guides/LazySplit.md rename to Guides/Split.md index a812756..db97306 100644 --- a/Guides/LazySplit.md +++ b/Guides/Split.md @@ -1,7 +1,7 @@ -# LazySplit +# Split -[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/LazySplit.swift) | - [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/LazySplitTests.swift)] +[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Split.swift) | + [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/SplitTests.swift)] Lazily-evaluating versions of [`split(maxSplits:omittingEmptySubsequences:whereSeparator:)`](https://developer.apple.com/documentation/swift/sequence/3128814-split) diff --git a/Guides/Stride.md b/Guides/Stride.md index 2914bc8..7eb9e7f 100644 --- a/Guides/Stride.md +++ b/Guides/Stride.md @@ -3,7 +3,7 @@ [[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Stride.swift) | [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/StrideTests.swift)] -A type that steps over sequence elements by the specified amount. +Step over the elements of a sequence elements by a specified amount. This is available through the `striding(by:)` method on any `Sequence`. @@ -11,29 +11,35 @@ This is available through the `striding(by:)` method on any `Sequence`. (0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10] ``` -If the stride is larger than the count, the resulting wrapper only contains the -first element. +If the stride is larger than the length of the sequence, the resulting wrapper +only contains the first element. The stride amount must be a positive value. ## Detailed Design -The `striding(by:)` method is declared as a `Sequence` extension, and returns a -`StridingSequence` type: +The `striding(by:)` method is declared in extension of both `Sequence` and +`Collection`: ```swift extension Sequence { - public func striding(by step: Int) -> StridingSequence + public func striding(by step: Int) -> StridingSequence +} + +extension Collection { + public func striding(by step: Int) -> StridingCollection } ``` -A custom `Index` type is defined so that it's not possible to get confused when -trying to access an index of the stride collection. - -```swift -[0, 1, 2, 3, 4].striding(by: 2)[1] // == 1 -[0, 1, 2, 3, 4].striding(by: 2).map { $0 }[1] // == 2 -``` +The reason for this distinction is subtle. The `StridingSequence.Iterator` type +is unable to skip over multiple elements of the wrapped iterator at once since +that's not part of `IteratorProtocol`'s interface. In order to efficiently +stride over collections that provide a fast way of skipping multiple elements at +once, the `StridingCollection` type was added which does not provide a custom +`Iterator` type and therefore always strides over the underlying collection in +the fastest way possible. See the related +[GitHub issue](https://github.com/apple/swift-algorithms/issues/63) for more +information. A careful thought was given to the composition of these strides by giving a custom implementation to `index(_:offsetBy:limitedBy)` which multiplies the diff --git a/Guides/Windows.md b/Guides/Windows.md index c7c09d7..8725d99 100644 --- a/Guides/Windows.md +++ b/Guides/Windows.md @@ -36,7 +36,7 @@ collection is empty. The resulting `WindowsCollection` type is a collection, with conditional conformance to the `BidirectionalCollection`, `RandomAccessCollection`, and -`LazyCollectionProtocol` protocols when the base collection conforms. +`LazySequenceProtocol` protocols when the base collection conforms. ### Complexity diff --git a/README.md b/README.md index c5bc98d..b3989d2 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ Read more about the package, and the intent behind it, in the [announcement on s - [`interspersed(with:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Intersperse.md): Place a value between every two elements of a sequence. - [`partitioningIndex(where:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Partition.md): Returns the starting index of the partition of a collection that matches a predicate. - [`reductions(_:)`, `reductions(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Reductions.md): Returns all the intermediate states of reducing the elements of a sequence or collection. -- [`split(maxSplits:omittingEmptySubsequences:whereSeparator)`, `split(separator:maxSplits:omittingEmptySubsequences)`](https://github.com/apple/swift-algorithms/blob/main/Guides/LazySplit.md): Lazy versions of the Standard Library's eager operations that split sequences and collections into subsequences separated by the specified separator element. +- [`split(maxSplits:omittingEmptySubsequences:whereSeparator)`, `split(separator:maxSplits:omittingEmptySubsequences)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Split.md): Lazy versions of the Standard Library's eager operations that split sequences and collections into subsequences separated by the specified separator element. - [`windows(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Windows.md): Breaks a collection into overlapping subsequences where elements are slices from the original collection. ## Adding Swift Algorithms as a Dependency diff --git a/Sources/Algorithms/AdjacentPairs.swift b/Sources/Algorithms/AdjacentPairs.swift index 002a07a..1c1fd71 100644 --- a/Sources/Algorithms/AdjacentPairs.swift +++ b/Sources/Algorithms/AdjacentPairs.swift @@ -14,9 +14,8 @@ extension Sequence { /// /// In the `AdjacentPairsSequence` returned by this method, the elements of /// the *i*th pair are the *i*th and *(i+1)*th elements of the underlying - /// sequence. - /// The following example uses the `adjacentPairs()` method to iterate over - /// adjacent pairs of integers: + /// sequence. The following example uses the `adjacentPairs()` method to + /// iterate over adjacent pairs of integers: /// /// for pair in (1...).prefix(5).adjacentPairs() { /// print(pair) @@ -69,7 +68,8 @@ public struct AdjacentPairsSequence { } extension AdjacentPairsSequence { - /// The iterator for an `AdjacentPairsSequence` or `AdjacentPairsCollection`. + /// The iterator for an `AdjacentPairsSequence` or `AdjacentPairsCollection` + /// instance. public struct Iterator { @usableFromInline internal var base: Base.Iterator @@ -126,44 +126,20 @@ public struct AdjacentPairsCollection { @usableFromInline internal let base: Base - public let startIndex: Index + @usableFromInline + internal let secondBaseIndex: Base.Index @inlinable internal init(base: Base) { self.base = base - - // Lazily build the end index, since we can't use the instance - // property pre-initialization - var endIndex: Index { - Index(first: base.endIndex, second: base.endIndex) - } - - // Precompute `startIndex` to ensure O(1) behavior. - guard !base.isEmpty else { - self.startIndex = endIndex - return - } - - // If there's only one element (i.e. the second index of base == endIndex) - // then this collection should be empty. - let secondIndex = base.index(after: base.startIndex) - self.startIndex = secondIndex == base.endIndex - ? endIndex - : Index(first: base.startIndex, second: secondIndex) + self.secondBaseIndex = base.isEmpty + ? base.endIndex + : base.index(after: base.startIndex) } } extension AdjacentPairsCollection { - public typealias Iterator = AdjacentPairsSequence.Iterator - - @inlinable - public func makeIterator() -> Iterator { - Iterator(base: base.makeIterator()) - } -} - -extension AdjacentPairsCollection { - /// A position in an `AdjacentPairsCollection`. + /// A position in an `AdjacentPairsCollection` instance. public struct Index: Comparable { @usableFromInline internal var first: Base.Index @@ -178,7 +154,7 @@ extension AdjacentPairsCollection { } @inlinable - public static func ==(lhs: Index, rhs: Index) -> Bool { + public static func == (lhs: Index, rhs: Index) -> Bool { lhs.first == rhs.first } @@ -190,6 +166,13 @@ extension AdjacentPairsCollection { } extension AdjacentPairsCollection: Collection { + @inlinable + public var startIndex: Index { + Index( + first: secondBaseIndex == base.endIndex ? base.endIndex : base.startIndex, + second: secondBaseIndex) + } + @inlinable public var endIndex: Index { Index(first: base.endIndex, second: base.endIndex) @@ -305,7 +288,7 @@ extension AdjacentPairsCollection: RandomAccessCollection where Base: RandomAccessCollection {} extension AdjacentPairsCollection: LazySequenceProtocol, LazyCollectionProtocol - where Base: LazyCollectionProtocol {} + where Base: LazySequenceProtocol {} extension AdjacentPairsCollection.Index: Hashable where Base.Index: Hashable { @inlinable diff --git a/Sources/Algorithms/Chain.swift b/Sources/Algorithms/Chain.swift index d8920d4..1a7e9b1 100644 --- a/Sources/Algorithms/Chain.swift +++ b/Sources/Algorithms/Chain.swift @@ -29,7 +29,7 @@ public struct Chain2Sequence } extension Chain2Sequence: Sequence { - /// The iterator for a `Chain2` sequence. + /// The iterator for a `Chain2Sequence` instance. public struct Iterator: IteratorProtocol { @usableFromInline internal var iterator1: Base1.Iterator @@ -56,7 +56,7 @@ extension Chain2Sequence: Sequence { } extension Chain2Sequence: Collection where Base1: Collection, Base2: Collection { - /// A position in a `Chain2` collection. + /// A position in a `Chain2Sequence` instance. public struct Index: Comparable { // The internal index representation, which can either be an index of the // first collection or the second. The `endIndex` of the first collection @@ -64,7 +64,7 @@ extension Chain2Sequence: Collection where Base1: Collection, Base2: Collection // from the penultimate index of the first collection to the start of the // second. @usableFromInline - internal enum Representation : Equatable { + internal enum Representation: Equatable { case first(Base1.Index) case second(Base2.Index) } @@ -115,7 +115,7 @@ extension Chain2Sequence: Collection where Base1: Collection, Base2: Collection @inlinable public var endIndex: Index { - return Index(second: base2.endIndex) + Index(second: base2.endIndex) } @inlinable diff --git a/Sources/Algorithms/Chunked.swift b/Sources/Algorithms/Chunked.swift index c9af28b..314262a 100644 --- a/Sources/Algorithms/Chunked.swift +++ b/Sources/Algorithms/Chunked.swift @@ -26,9 +26,9 @@ public struct ChunkedByCollection { @usableFromInline internal let belongInSameGroup: (Subject, Subject) -> Bool - /// The upper bound of the first chunk. + /// The end index of the first chunk. @usableFromInline - internal var firstUpperBound: Base.Index + internal var endOfFirstChunk: Base.Index @inlinable internal init( @@ -39,15 +39,15 @@ public struct ChunkedByCollection { self.base = base self.projection = projection self.belongInSameGroup = belongInSameGroup - self.firstUpperBound = base.startIndex + self.endOfFirstChunk = base.startIndex if !base.isEmpty { - firstUpperBound = endOfChunk(startingAt: base.startIndex) + endOfFirstChunk = endOfChunk(startingAt: base.startIndex) } } } -extension ChunkedByCollection: LazyCollectionProtocol { +extension ChunkedByCollection: Collection { /// A position in a chunked collection. public struct Index: Comparable { /// The range corresponding to the chunk at this position. @@ -88,7 +88,7 @@ extension ChunkedByCollection: LazyCollectionProtocol { @inlinable public var startIndex: Index { - Index(base.startIndex.. = ChunkedByCollection +extension ChunkedByCollection: LazyCollectionProtocol {} @available(*, deprecated, renamed: "ChunkedByCollection") -public typealias Chunked = ChunkedByCollection +public typealias LazyChunked + = ChunkedByCollection @available(*, deprecated, renamed: "ChunkedByCollection") -public typealias ChunkedBy = 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 ChunkedOnCollection { +public struct ChunkedOnCollection { @usableFromInline internal var chunked: ChunkedByCollection @inlinable internal init( base: Base, - projection: @escaping (Base.Element) -> Subject, - belongInSameGroup: @escaping (Subject, Subject) -> Bool + projection: @escaping (Base.Element) -> Subject ) { - self.chunked = ChunkedByCollection(base: base, projection: projection, belongInSameGroup: belongInSameGroup) + self.chunked = ChunkedByCollection( + base: base, + projection: projection, + belongInSameGroup: ==) } } -extension ChunkedOnCollection: LazyCollectionProtocol { +extension ChunkedOnCollection: Collection { public typealias Index = ChunkedByCollection.Index @inlinable @@ -192,17 +199,22 @@ extension ChunkedOnCollection: LazyCollectionProtocol { } } -extension ChunkedOnCollection: BidirectionalCollection where Base: BidirectionalCollection { +extension ChunkedOnCollection: BidirectionalCollection + where Base: BidirectionalCollection +{ + @inlinable public func index(before i: Index) -> Index { chunked.index(before: i) } } +extension ChunkedOnCollection: LazyCollectionProtocol {} + //===----------------------------------------------------------------------===// // lazy.chunked(by:) / lazy.chunked(on:) //===----------------------------------------------------------------------===// -extension LazyCollectionProtocol { +extension LazySequenceProtocol where Self: Collection, Elements: Collection { /// Returns a lazy collection of subsequences of this collection, chunked by /// the given predicate. /// @@ -222,13 +234,12 @@ extension LazyCollectionProtocol { /// /// - Complexity: O(*n*), because the start index is pre-computed. @inlinable - public func chunked( + public func chunked( on projection: @escaping (Element) -> Subject ) -> ChunkedOnCollection { ChunkedOnCollection( base: elements, - projection: projection, - belongInSameGroup: ==) + projection: projection) } } @@ -237,8 +248,8 @@ extension LazyCollectionProtocol { //===----------------------------------------------------------------------===// extension Collection { - /// Returns a collection of subsequences of this collection, chunked by - /// the given predicate. + /// Returns a collection of subsequences of this collection, chunked by the + /// given predicate. /// /// - Complexity: O(*n*), where *n* is the length of this collection. @inlinable @@ -260,7 +271,7 @@ extension Collection { } if start != endIndex { - result.append(self[start.. { - public typealias Element = Base.SubSequence @usableFromInline @@ -321,10 +333,10 @@ public struct ChunksOfCountCollection { internal let chunkCount: Int @usableFromInline - internal var startUpperBound: Base.Index + internal var endOfFirstChunk: Base.Index - /// Creates a view instance that presents the elements of `base` - /// in `SubSequence` chunks of the given count. + /// Creates a view instance that presents the elements of `base` in + /// `SubSequence` chunks of the given count. /// /// - Complexity: O(*n*), because the start index is pre-computed. @inlinable @@ -332,9 +344,9 @@ public struct ChunksOfCountCollection { self.base = _base self.chunkCount = _chunkCount - // Compute the start index upfront in order to make - // start index a O(1) lookup. - self.startUpperBound = _base.index( + // Compute the start index upfront in order to make start index a O(1) + // lookup. + self.endOfFirstChunk = _base.index( _base.startIndex, offsetBy: _chunkCount, limitedBy: _base.endIndex ) ?? _base.endIndex @@ -355,8 +367,9 @@ extension ChunksOfCountCollection: Collection { /// - Complexity: O(1) @inlinable public var startIndex: Index { - Index(_baseRange: base.startIndex.. Element { - precondition(i < endIndex, "Index out of range") + precondition(i != endIndex, "Index out of range") return base[i.baseRange] } @inlinable public func index(after i: Index) -> Index { - precondition(i < endIndex, "Advancing past end index") + precondition(i != endIndex, "Advancing past end index") let baseIdx = base.index( i.baseRange.upperBound, offsetBy: chunkCount, limitedBy: base.endIndex @@ -399,11 +412,11 @@ extension ChunksOfCountCollection: where Base: RandomAccessCollection { @inlinable public func index(before i: Index) -> Index { - precondition(i > startIndex, "Advancing past start index") + precondition(i != startIndex, "Advancing past start index") var offset = chunkCount if i.baseRange.lowerBound == base.endIndex { - let remainder = base.count%chunkCount + let remainder = base.count % chunkCount if remainder != 0 { offset = remainder } @@ -488,9 +501,9 @@ extension ChunksOfCountCollection { let remainder = base.count%chunkCount // We have to take it into account when calculating offsets. if remainder != 0 { - // Distance "minus" one(at this point distance is negative) - // because we need to adjust for the last position that have - // a variadic(remainder) number of elements. + // Distance "minus" one(at this point distance is negative) because we + // need to adjust for the last position that have a variadic(remainder) + // number of elements. return ((distance + 1) * chunkCount) - remainder } } @@ -524,14 +537,13 @@ extension ChunksOfCountCollection { if let limit = limit { if baseIdx == nil { - // If we past the bounds while advancing forward and the - // limit is the `endIndex`, since the computation on base - // don't take into account the remainder, we have to make - // sure that passing the bound was because of the distance - // not just because of a remainder. Special casing is less - // expensive than always use count(which could be O(n) for - // non-random access collection base) to compute the base - // distance taking remainder into account. + // If we past the bounds while advancing forward and the limit is the + // `endIndex`, since the computation on base don't take into account the + // remainder, we have to make sure that passing the bound was because of + // the distance not just because of a remainder. Special casing is less + // expensive than always use count(which could be O(n) for non-random + // access collection base) to compute the base distance taking remainder + // into account. if baseDistance > 0 && limit == endIndex { if self.distance(from: i, to: limit) < distance { return nil @@ -558,13 +570,13 @@ extension ChunksOfCountCollection { } extension Collection { - /// Returns a `ChunkedCollection` view presenting the elements - /// in chunks with count of the given count parameter. + /// Returns a `ChunksOfCountCollection` view presenting the elements in + /// chunks with count of the given count parameter. /// - /// - Parameter size: The size of the chunks. If the count parameter - /// is evenly divided by the count of the base `Collection` all the - /// chunks will have the count equals to size. - /// Otherwise, the last chunk will contain the remaining elements. + /// - Parameter count: The size of the chunks. If the count parameter is + /// evenly divided by the count of the base `Collection` all the chunks will + /// have the count equals to size. Otherwise, the last chunk will contain + /// the remaining elements. /// /// let c = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] /// print(c.chunks(ofCount: 5).map(Array.init)) @@ -583,8 +595,5 @@ extension Collection { extension ChunksOfCountCollection.Index: Hashable where Base.Index: Hashable {} -// Lazy conditional conformance. -extension ChunksOfCountCollection: LazySequenceProtocol +extension ChunksOfCountCollection: LazySequenceProtocol, LazyCollectionProtocol where Base: LazySequenceProtocol {} -extension ChunksOfCountCollection: LazyCollectionProtocol - where Base: LazyCollectionProtocol {} diff --git a/Sources/Algorithms/Combinations.swift b/Sources/Algorithms/Combinations.swift index 5034f31..2f26e9c 100644 --- a/Sources/Algorithms/Combinations.swift +++ b/Sources/Algorithms/Combinations.swift @@ -19,12 +19,15 @@ public struct CombinationsSequence { internal let baseCount: Int /// The range of accepted sizes of combinations. + /// /// - Note: This may be `nil` if the attempted range entirely exceeds the /// upper bounds of the size of the `base` collection. @usableFromInline internal let kRange: Range? - /// Initializes a `Combinations` for all combinations of `base` of size `k`. + /// Initializes a `CombinationsSequence` for all combinations of `base` of + /// size `k`. + /// /// - Parameters: /// - base: The collection to iterate over for combinations. /// - k: The expected size of each combination. @@ -33,8 +36,9 @@ public struct CombinationsSequence { self.init(base, kRange: k...k) } - /// Initializes a `Combinations` for all combinations of `base` of sizes - /// within a given range. + /// Initializes a `CombinationsSequence` for all combinations of `base` of + /// sizes within a given range. + /// /// - Parameters: /// - base: The collection to iterate over for combinations. /// - kRange: The range of accepted sizes of combinations. @@ -77,12 +81,13 @@ public struct CombinationsSequence { } extension CombinationsSequence: Sequence { - /// The iterator for a `Combinations` instance. + /// The iterator for a `CombinationsSequence` instance. public struct Iterator: IteratorProtocol { @usableFromInline internal let base: Base /// The current range of accepted sizes of combinations. + /// /// - Note: The range is contracted until empty while iterating over /// combinations of different sizes. When the range is empty, iteration is /// finished. @@ -175,12 +180,14 @@ extension CombinationsSequence: Sequence { } } + @inlinable public func makeIterator() -> Iterator { Iterator(self) } } -extension CombinationsSequence: LazySequenceProtocol where Base: LazySequenceProtocol {} +extension CombinationsSequence: LazySequenceProtocol + where Base: LazySequenceProtocol {} //===----------------------------------------------------------------------===// // combinations(ofCount:) @@ -243,16 +250,16 @@ extension Collection { /// limited range is empty, the resulting sequence has no elements. /// /// - Parameter kRange: The range of numbers of elements to include in each - /// combination. + /// combination. /// /// - Complexity: O(1) for random-access base collections. O(*n*) where *n* - /// is the number of elements in the base collection, since `Combinations` - /// accesses the `count` of the base collection. + /// is the number of elements in the base collection, since + /// `CombinationsSequence` accesses the `count` of the base collection. @inlinable public func combinations( ofCount kRange: R ) -> CombinationsSequence where R.Bound == Int { - return CombinationsSequence(self, kRange: kRange) + CombinationsSequence(self, kRange: kRange) } /// Returns a collection of combinations of this collection's elements, with @@ -282,8 +289,8 @@ extension Collection { /// - Parameter k: The number of elements to include in each combination. /// /// - Complexity: O(1) for random-access base collections. O(*n*) where *n* - /// is the number of elements in the base collection, since `Combinations` - /// accesses the `count` of the base collection. + /// is the number of elements in the base collection, since + /// `CombinationsSequence` accesses the `count` of the base collection. @inlinable public func combinations(ofCount k: Int) -> CombinationsSequence { precondition(k >= 0, "Can't have combinations with a negative number of elements.") diff --git a/Sources/Algorithms/Compacted.swift b/Sources/Algorithms/Compacted.swift index 788d34a..1e7ba48 100644 --- a/Sources/Algorithms/Compacted.swift +++ b/Sources/Algorithms/Compacted.swift @@ -9,7 +9,8 @@ // //===----------------------------------------------------------------------===// -/// A `Sequence` that iterates over every non-nil element from the original `Sequence`. +/// A `Sequence` that iterates over every non-nil element from the original +/// `Sequence`. public struct CompactedSequence: Sequence where Base.Element == Element? { @@ -42,14 +43,15 @@ public struct CompactedSequence: Sequence @inlinable public func makeIterator() -> Iterator { - return Iterator(base: base.makeIterator()) + Iterator(base: base.makeIterator()) } } extension Sequence { - /// Returns a new `Sequence` that iterates over every non-nil element - /// from the original `Sequence`. - /// It produces the same result as `c.compactMap { $0 }`. + /// Returns a new `Sequence` that iterates over every non-nil element from the + /// original `Sequence`. + /// + /// Produces the same result as `c.compactMap { $0 }`. /// /// let c = [1, nil, 2, 3, nil] /// for num in c.compacted() { @@ -71,7 +73,8 @@ extension Sequence { } } -/// A `Collection` that iterates over every non-nil element from the original `Collection`. +/// A `Collection` that iterates over every non-nil element from the original +/// `Collection`. public struct CompactedCollection: Collection where Base.Element == Element? { @@ -143,9 +146,10 @@ extension CompactedCollection.Index: Hashable where Base.Index: Hashable {} extension Collection { - /// Returns a new `Collection` that iterates over every non-nil element - /// from the original `Collection`. - /// It produces the same result as `c.compactMap { $0 }`. + /// Returns a new `Collection` that iterates over every non-nil element from + /// the original `Collection`. + /// + /// Produces the same result as `c.compactMap { $0 }`. /// /// let c = [1, nil, 2, 3, nil] /// for num in c.compacted() { @@ -163,7 +167,8 @@ extension Collection { /// original `Collection`. @inlinable public func compacted() -> CompactedCollection - where Element == Unwrapped? { + where Element == Unwrapped? + { CompactedCollection(base: self) } } @@ -175,7 +180,5 @@ extension Collection { extension CompactedSequence: LazySequenceProtocol where Base: LazySequenceProtocol {} -extension CompactedCollection: LazySequenceProtocol +extension CompactedCollection: LazySequenceProtocol, LazyCollectionProtocol where Base: LazySequenceProtocol {} -extension CompactedCollection: LazyCollectionProtocol - where Base: LazyCollectionProtocol {} diff --git a/Sources/Algorithms/Cycle.swift b/Sources/Algorithms/Cycle.swift index a92b4e4..23d1416 100644 --- a/Sources/Algorithms/Cycle.swift +++ b/Sources/Algorithms/Cycle.swift @@ -22,7 +22,7 @@ public struct CycledSequence { } extension CycledSequence: Sequence { - /// The iterator for a `Cycle` sequence. + /// The iterator for a `CycledSequence` instance. public struct Iterator: IteratorProtocol { @usableFromInline internal let base: Base @@ -58,7 +58,6 @@ extension CycledSequence: Sequence { extension CycledSequence: LazySequenceProtocol where Base: LazySequenceProtocol {} - /// A collection wrapper that repeats the elements of a base collection for a /// finite number of times. public struct CycledTimesCollection { @@ -76,7 +75,8 @@ extension CycledTimesCollection: Collection { public typealias Element = Base.Element public struct Index: Comparable { - /// The index corresponding to the Product2 index at this position. + /// The index corresponding to the `Product2Sequence` index at this + /// position. @usableFromInline internal let productIndex: Product2Sequence, Base>.Index @@ -134,11 +134,11 @@ extension CycledTimesCollection: Collection { offsetBy distance: Int, limitedBy limit: Index ) -> Index? { - guard let productIndex = product.index(i.productIndex, - offsetBy: distance, - limitedBy: limit.productIndex) else { - return nil - } + guard let productIndex = product.index( + i.productIndex, + offsetBy: distance, + limitedBy: limit.productIndex) + else { return nil } return Index(productIndex) } diff --git a/Sources/Algorithms/FirstNonNil.swift b/Sources/Algorithms/FirstNonNil.swift index 0c15c83..f9719f3 100644 --- a/Sources/Algorithms/FirstNonNil.swift +++ b/Sources/Algorithms/FirstNonNil.swift @@ -13,7 +13,7 @@ // firstNonNil(_:) //===----------------------------------------------------------------------===// -public extension Sequence { +extension Sequence { /// Returns the first non-`nil` result obtained from applying the given /// transformation to the elements of the sequence. /// @@ -30,7 +30,8 @@ public extension Sequence { /// /// - Complexity: O(*n*), where *n* is the number of elements at the start of /// the sequence that result in `nil` when applying the transformation. - func firstNonNil( + @inlinable + public func firstNonNil( _ transform: (Element) throws -> Result? ) rethrows -> Result? { for value in self { diff --git a/Sources/Algorithms/FlattenCollection.swift b/Sources/Algorithms/FlattenCollection.swift index d4b6f29..23b8a87 100644 --- a/Sources/Algorithms/FlattenCollection.swift +++ b/Sources/Algorithms/FlattenCollection.swift @@ -12,7 +12,9 @@ /// A collection consisting of all the elements contained in a collection of /// collections. @usableFromInline -internal struct FlattenCollection where Base.Element: Collection { +internal struct FlattenCollection + where Base.Element: Collection +{ @usableFromInline internal let base: Base @@ -97,7 +99,9 @@ extension FlattenCollection: Collection { guard let startInner = start.inner else { return 0 } guard start.outer != end.outer - else { return base[start.outer].distance(from: startInner, to: end.inner!) } + else { + return base[start.outer].distance(from: startInner, to: end.inner!) + } let firstPart = base[start.outer][startInner...].count let middlePart = base[start.outer.. { - /// The element type for an `Indexed` collection. - public typealias Element = (index: Base.Index, element: Base.Element) - /// The base collection. @usableFromInline internal let base: Base @@ -26,6 +23,9 @@ public struct IndexedCollection { } extension IndexedCollection: Collection { + /// The element type for an `IndexedCollection` collection. + public typealias Element = (index: Base.Index, element: Base.Element) + @inlinable public var startIndex: Base.Index { base.startIndex @@ -52,7 +52,11 @@ extension IndexedCollection: Collection { } @inlinable - public func index(_ i: Base.Index, offsetBy distance: Int, limitedBy limit: Base.Index) -> Base.Index? { + public func index( + _ i: Base.Index, + offsetBy distance: Int, + limitedBy limit: Base.Index + ) -> Base.Index? { base.index(i, offsetBy: distance, limitedBy: limit) } @@ -62,16 +66,20 @@ extension IndexedCollection: Collection { } } -extension IndexedCollection: 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 IndexedCollection: RandomAccessCollection where Base: RandomAccessCollection {} -extension IndexedCollection: LazySequenceProtocol where Base: LazySequenceProtocol {} -extension IndexedCollection: LazyCollectionProtocol where Base: LazyCollectionProtocol {} +extension IndexedCollection: RandomAccessCollection + where Base: RandomAccessCollection {} + +extension IndexedCollection: LazySequenceProtocol, LazyCollectionProtocol + where Base: LazySequenceProtocol {} //===----------------------------------------------------------------------===// // indexed() diff --git a/Sources/Algorithms/Intersperse.swift b/Sources/Algorithms/Intersperse.swift index b213586..706c4ea 100644 --- a/Sources/Algorithms/Intersperse.swift +++ b/Sources/Algorithms/Intersperse.swift @@ -13,8 +13,8 @@ // Intersperse //===----------------------------------------------------------------------===// -/// A sequence that presents the elements of a base sequence of elements -/// with a separator between each of those elements. +/// A sequence that presents the elements of a base sequence of elements with a +/// separator between each of those elements. public struct InterspersedSequence { @usableFromInline internal let base: Base @@ -30,8 +30,15 @@ public struct InterspersedSequence { } extension InterspersedSequence: Sequence { - /// The iterator for an `Intersperse` sequence. + /// The iterator for an `InterspersedSequence` sequence. public struct Iterator: IteratorProtocol { + @usableFromInline + internal enum State { + case start + case element(Base.Element) + case separator + } + @usableFromInline internal var iterator: Base.Iterator @@ -46,13 +53,6 @@ extension InterspersedSequence: Sequence { self.iterator = iterator self.separator = separator } - - @usableFromInline - enum State { - case start - case element(Base.Element) - case separator - } @inlinable public mutating func next() -> Base.Element? { @@ -82,7 +82,7 @@ extension InterspersedSequence: Sequence { } extension InterspersedSequence: Collection where Base: Collection { - /// A position in an `Intersperse` collection. + /// A position in an `InterspersedSequence` instance. public struct Index: Comparable { @usableFromInline internal enum Representation: Equatable { @@ -278,7 +278,7 @@ extension InterspersedSequence: LazySequenceProtocol where Base: LazySequenceProtocol {} extension InterspersedSequence: LazyCollectionProtocol - where Base: LazyCollectionProtocol {} + where Base: LazySequenceProtocol & Collection {} //===----------------------------------------------------------------------===// // InterspersedMap @@ -303,6 +303,13 @@ internal struct InterspersedMapSequence { extension InterspersedMapSequence: Sequence { @usableFromInline internal struct Iterator: IteratorProtocol { + @usableFromInline + internal enum State { + case start + case element(Base.Element) + case separator(previous: Base.Element) + } + @usableFromInline internal var base: Base.Iterator @@ -325,13 +332,6 @@ extension InterspersedMapSequence: Sequence { self.transform = transform self.separator = separator } - - @usableFromInline - internal enum State { - case start - case element(Base.Element) - case separator(previous: Base.Element) - } @inlinable internal mutating func next() -> Result? { @@ -364,7 +364,7 @@ extension InterspersedMapSequence: Collection where Base: Collection { @usableFromInline internal struct Index: Comparable { @usableFromInline - internal enum Representation: Equatable { + internal enum Representation { case element(Base.Index) case separator(previous: Base.Index, next: Base.Index) } @@ -577,20 +577,31 @@ extension InterspersedMapSequence: BidirectionalCollection } } -extension InterspersedMapSequence.Index.Representation: Hashable - where Base.Index: Hashable {} +extension InterspersedMapSequence.Index: Hashable + where Base.Index: Hashable +{ + @inlinable + internal func hash(into hasher: inout Hasher) { + switch representation { + case .element(let base): + hasher.combine(false) + hasher.combine(base) + case .separator(_, let next): + hasher.combine(true) + hasher.combine(next) + } + } +} -extension InterspersedMapSequence: LazySequenceProtocol - where Base: LazySequenceProtocol {} +extension InterspersedMapSequence: LazySequenceProtocol {} extension InterspersedMapSequence: LazyCollectionProtocol - where Base: LazyCollectionProtocol {} + where Base: Collection {} //===----------------------------------------------------------------------===// // interspersed(with:) //===----------------------------------------------------------------------===// extension Sequence { - /// Returns a sequence containing elements of this sequence with the given /// separator inserted in between each element. /// @@ -620,13 +631,15 @@ extension Sequence { /// /// - Complexity: O(1) @inlinable - public func interspersed(with separator: Element) -> InterspersedSequence { + public func interspersed( + with separator: Element + ) -> InterspersedSequence { InterspersedSequence(base: self, separator: separator) } } //===----------------------------------------------------------------------===// -// lazy.interspersed(_:with:) +// lazy.interspersedMap(_:with:) //===----------------------------------------------------------------------===// extension LazySequenceProtocol { @@ -647,7 +660,10 @@ extension LazySequenceProtocol { internal func interspersedMap( _ transform: @escaping (Element) -> Result, with separator: @escaping (Element, Element) -> Result - ) -> InterspersedMapSequence { - InterspersedMapSequence(base: self, transform: transform, separator: separator) + ) -> InterspersedMapSequence { + InterspersedMapSequence( + base: elements, + transform: transform, + separator: separator) } } diff --git a/Sources/Algorithms/Joined.swift b/Sources/Algorithms/Joined.swift index 9b02cec..13f2f69 100644 --- a/Sources/Algorithms/Joined.swift +++ b/Sources/Algorithms/Joined.swift @@ -71,7 +71,7 @@ public struct JoinedByClosureSequence { @usableFromInline internal typealias Inner = FlattenSequence, EitherSequence>> + Base, EitherSequence>> @usableFromInline internal let inner: Inner @@ -111,8 +111,7 @@ extension JoinedByClosureSequence: Sequence { } } -extension JoinedByClosureSequence: LazySequenceProtocol - where Base: LazySequenceProtocol {} +extension JoinedByClosureSequence: LazySequenceProtocol {} //===----------------------------------------------------------------------===// // JoinedByCollection @@ -212,10 +211,8 @@ extension JoinedByCollection: BidirectionalCollection } } -extension JoinedByCollection: LazySequenceProtocol +extension JoinedByCollection: LazySequenceProtocol, LazyCollectionProtocol where Base: LazySequenceProtocol {} -extension JoinedByCollection: LazyCollectionProtocol - where Base: LazyCollectionProtocol {} //===----------------------------------------------------------------------===// // JoinedByClosureCollection @@ -229,7 +226,7 @@ public struct JoinedByClosureCollection { @usableFromInline internal typealias Inner = FlattenCollection, EitherSequence>> + Base, EitherSequence>> @usableFromInline internal let inner: Inner @@ -320,10 +317,7 @@ extension JoinedByClosureCollection: BidirectionalCollection } } -extension JoinedByClosureCollection: LazySequenceProtocol - where Base: LazySequenceProtocol {} -extension JoinedByClosureCollection: LazyCollectionProtocol - where Base: LazyCollectionProtocol {} +extension JoinedByClosureCollection: LazyCollectionProtocol {} //===----------------------------------------------------------------------===// // Sequence.joined(by:) @@ -420,7 +414,7 @@ extension LazySequenceProtocol where Element: Sequence { @inlinable public func joined( by separator: @escaping (Element, Element) -> Element.Element - ) -> JoinedByClosureSequence> { + ) -> JoinedByClosureSequence> { joined(by: { CollectionOfOne(separator($0, $1)) }) } @@ -429,8 +423,8 @@ extension LazySequenceProtocol where Element: Sequence { @inlinable public func joined( by separator: @escaping (Element, Element) -> Separator - ) -> JoinedByClosureSequence { - JoinedByClosureSequence(base: self, separator: separator) + ) -> JoinedByClosureSequence { + JoinedByClosureSequence(base: elements, separator: separator) } } @@ -469,17 +463,17 @@ extension Collection where Element: Collection { } //===----------------------------------------------------------------------===// -// LazyCollectionProtocol.joined(by:) +// LazySequenceProtocol.joined(by:) where Self: Collection //===----------------------------------------------------------------------===// -extension LazyCollectionProtocol where Element: Collection { +extension LazySequenceProtocol where Elements: Collection, Element: Collection { /// Returns the concatenation of the elements in this collection of /// collections, inserting the separator produced by the closure between each /// sequence. @inlinable public func joined( by separator: @escaping (Element, Element) -> Element.Element - ) -> JoinedByClosureCollection> { + ) -> JoinedByClosureCollection> { joined(by: { CollectionOfOne(separator($0, $1)) }) } @@ -489,7 +483,7 @@ extension LazyCollectionProtocol where Element: Collection { @inlinable public func joined( by separator: @escaping (Element, Element) -> Separator - ) -> JoinedByClosureCollection { - JoinedByClosureCollection(base: self, separator: separator) + ) -> JoinedByClosureCollection { + JoinedByClosureCollection(base: elements, separator: separator) } } diff --git a/Sources/Algorithms/MinMax.swift b/Sources/Algorithms/MinMax.swift index 045dd35..1ca66cb 100644 --- a/Sources/Algorithms/MinMax.swift +++ b/Sources/Algorithms/MinMax.swift @@ -190,7 +190,7 @@ extension Sequence where Element: Comparable { /// sequence and *k* is `count`. @inlinable public func min(count: Int) -> [Element] { - return min(count: count, sortedBy: <) + min(count: count, sortedBy: <) } /// Returns the largest elements of this sequence. @@ -216,7 +216,7 @@ extension Sequence where Element: Comparable { /// sequence and *k* is `count`. @inlinable public func max(count: Int) -> [Element] { - return max(count: count, sortedBy: <) + max(count: count, sortedBy: <) } } @@ -354,7 +354,7 @@ extension Collection where Element: Comparable { /// collection and *k* is `count`. @inlinable public func min(count: Int) -> [Element] { - return min(count: count, sortedBy: <) + min(count: count, sortedBy: <) } /// Returns the largest elements of this collection. @@ -380,7 +380,7 @@ extension Collection where Element: Comparable { /// collection and *k* is `count`. @inlinable public func max(count: Int) -> [Element] { - return max(count: count, sortedBy: <) + max(count: count, sortedBy: <) } } @@ -392,9 +392,8 @@ extension Sequence { /// Returns both the minimum and maximum elements in the sequence, using the /// given predicate as the comparison between elements. /// - /// The predicate must be a *strict weak ordering* over the elements. That - /// is, for any elements `a`, `b`, and `c`, the following conditions must - /// hold: + /// The predicate must be a *strict weak ordering* over the elements. That is, + /// for any elements `a`, `b`, and `c`, the following conditions must hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are @@ -405,9 +404,9 @@ extension Sequence { /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// - /// This example shows how to use the `minAndMax(by:)` method on a - /// dictionary to find the key-value pair with the lowest value and the pair - /// with the highest value. + /// This example shows how to use the `minAndMax(by:)` method on a dictionary + /// to find the key-value pair with the lowest value and the pair with the + /// highest value. /// /// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156] /// if let extremeHues = hues.minAndMax(by: {$0.value < $1.value}) { @@ -419,9 +418,9 @@ extension Sequence { /// /// - Precondition: The sequence is finite. /// - /// - Parameter areInIncreasingOrder: A predicate that returns `true` - /// if its first argument should be ordered before its second - /// argument; otherwise, `false`. + /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its + /// first argument should be ordered before its second argument; otherwise, + /// `false`. /// - Returns: A tuple with the sequence's minimum element, followed by its /// maximum element. If the sequence provides multiple qualifying minimum /// elements, the first equivalent element is returned; of multiple maximum @@ -429,6 +428,7 @@ extension Sequence { /// method returns `nil`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. + @inlinable public func minAndMax( by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows -> (min: Element, max: Element)? { @@ -479,6 +479,6 @@ extension Sequence where Element: Comparable { /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func minAndMax() -> (min: Element, max: Element)? { - return minAndMax(by: <) + minAndMax(by: <) } } diff --git a/Sources/Algorithms/Partition.swift b/Sources/Algorithms/Partition.swift index 66a0b01..48f1b1e 100644 --- a/Sources/Algorithms/Partition.swift +++ b/Sources/Algorithms/Partition.swift @@ -14,9 +14,9 @@ //===----------------------------------------------------------------------===// extension MutableCollection { - /// Moves all elements satisfying `belongsInSecondPartition` into a suffix - /// of the collection, preserving their relative order, and returns the - /// start of the resulting suffix. + /// Moves all elements satisfying `belongsInSecondPartition` into a suffix of + /// the collection, preserving their relative order, and returns the start of + /// the resulting suffix. /// /// - Complexity: O(*n* log *n*), where *n* is the number of elements. /// - Precondition: @@ -25,7 +25,7 @@ extension MutableCollection { internal mutating func stablePartition( count n: Int, subrange: Range, - by belongsInSecondPartition: (Element) throws-> Bool + by belongsInSecondPartition: (Element) throws -> Bool ) rethrows -> Index { if n == 0 { return subrange.lowerBound } if n == 1 { @@ -138,22 +138,22 @@ extension MutableCollection where Self: BidirectionalCollection { // * predicate(self[i]) == true, for i in hi ..< endIndex Loop: while true { - FindLo: repeat { + FindLo: do { while lo < hi { if try belongsInSecondPartition(self[lo]) { break FindLo } formIndex(after: &lo) } break Loop - } while false + } - FindHi: repeat { + FindHi: do { formIndex(before: &hi) while lo < hi { if try !belongsInSecondPartition(self[hi]) { break FindHi } formIndex(before: &hi) } break Loop - } while false + } swapAt(lo, hi) formIndex(after: &lo) @@ -173,8 +173,8 @@ extension Collection { /// /// The collection must already be partitioned according to the predicate. /// That is, there should be an index `i` where for every element in - /// `collection[.. { internal let baseCount: Int /// The range of accepted sizes of permutations. + /// /// - Note: This may be empty if the attempted range entirely exceeds the /// bounds of the size of the `base` collection. @usableFromInline internal let kRange: Range - /// Initializes a `Permutations` for all permutations of `base` of size `k`. + /// Initializes a `PermutationsSequence` for all permutations of `base` of + /// size `k`. + /// /// - Parameters: /// - base: The collection to iterate over for permutations /// - k: The expected size of each permutation, or `nil` (default) to @@ -106,8 +109,9 @@ public struct PermutationsSequence { self.init(base, kRange: kRange) } - /// Initializes a `Permutations` for all combinations of `base` of sizes - /// within a given range. + /// Initializes a `PermutationsSequence` for all combinations of `base` of + /// sizes within a given range. + /// /// - Parameters: /// - base: The collection to iterate over for permutations. /// - kRange: The range of accepted sizes of permutations, or `nil` to @@ -128,14 +132,14 @@ public struct PermutationsSequence { /// The total number of permutations. @inlinable public var count: Int { - return kRange.map { + kRange.map { stride(from: baseCount, to: baseCount - $0, by: -1).reduce(1, *) }.reduce(0, +) } } extension PermutationsSequence: Sequence { - /// The iterator for a `Permutations` instance. + /// The iterator for a `PermutationsSequence` instance. public struct Iterator: IteratorProtocol { @usableFromInline internal let base: Base @@ -259,7 +263,8 @@ extension PermutationsSequence: Sequence { } } -extension PermutationsSequence: LazySequenceProtocol where Base: LazySequenceProtocol {} +extension PermutationsSequence: LazySequenceProtocol + where Base: LazySequenceProtocol {} //===----------------------------------------------------------------------===// // permutations(ofCount:) @@ -320,13 +325,13 @@ extension Collection { /// results in an empty sequence. /// /// - Complexity: O(1) for random-access base collections. O(*n*) where *n* - /// is the number of elements in the base collection, since `Permutations` - /// accesses the `count` of the base collection. + /// is the number of elements in the base collection, since + /// `PermutationsSequence` accesses the `count` of the base collection. @inlinable public func permutations( ofCount kRange: R ) -> PermutationsSequence where R.Bound == Int { - return PermutationsSequence(self, kRange: kRange) + PermutationsSequence(self, kRange: kRange) } /// Returns a collection of the permutations of this collection of the @@ -376,8 +381,8 @@ extension Collection { /// this collection, the resulting sequence is empty. /// /// - Complexity: O(1) for random-access base collections. O(*n*) where *n* - /// is the number of elements in the base collection, since `Permutations` - /// accesses the `count` of the base collection. + /// is the number of elements in the base collection, since + /// `PermutationsSequence` accesses the `count` of the base collection. @inlinable public func permutations(ofCount k: Int? = nil) -> PermutationsSequence { precondition( @@ -394,7 +399,7 @@ extension Collection { /// A sequence of the unique permutations of the elements of a sequence or /// collection. /// -/// To create a `UniquePermutations` instance, call one of the +/// To create a `UniquePermutationsSequence` instance, call one of the /// `uniquePermutations` methods on your collection. public struct UniquePermutationsSequence { /// The base collection to iterate over for permutations. @@ -441,7 +446,7 @@ extension UniquePermutationsSequence where Base.Element: Hashable { } extension UniquePermutationsSequence: Sequence { - /// The iterator for a `UniquePermutations` instance. + /// The iterator for a `UniquePermutationsSequence` instance. public struct Iterator: IteratorProtocol { @usableFromInline internal let base: Base @@ -496,7 +501,8 @@ extension UniquePermutationsSequence: Sequence { } } -extension UniquePermutationsSequence: 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,7 +543,10 @@ 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) -> UniquePermutationsSequence { + @inlinable + public func uniquePermutations(ofCount k: Int? = nil) + -> UniquePermutationsSequence + { if let k = k { return UniquePermutationsSequence(self, k ..< (k + 1)) } else { @@ -574,9 +583,10 @@ extension Collection where Element: Hashable { /// /// - Complexity: O(*n*), where *n* is the number of elements in this /// collection. - public func uniquePermutations(ofCount kRange: R) -> UniquePermutationsSequence - where R.Bound == Int - { + @inlinable + public func uniquePermutations( + ofCount kRange: R + ) -> UniquePermutationsSequence where R.Bound == Int { UniquePermutationsSequence(self, kRange) } } diff --git a/Sources/Algorithms/Product.swift b/Sources/Algorithms/Product.swift index bbcdf29..d5611e9 100644 --- a/Sources/Algorithms/Product.swift +++ b/Sources/Algorithms/Product.swift @@ -29,7 +29,7 @@ public struct Product2Sequence { extension Product2Sequence: Sequence { public typealias Element = (Base1.Element, Base2.Element) - /// The iterator for a `Product2` sequence. + /// The iterator for a `Product2Sequence` sequence. public struct Iterator: IteratorProtocol { @usableFromInline internal var i1: Base1.Iterator @@ -83,13 +83,14 @@ extension Product2Sequence: Sequence { } } + @inlinable public func makeIterator() -> Iterator { - return Iterator(self) + Iterator(self) } } extension Product2Sequence: Collection where Base1: Collection { - /// The index type for a `Product2` collection. + /// The index type for a `Product2Sequence` collection. public struct Index: Comparable { @usableFromInline internal var i1: Base1.Index @@ -439,7 +440,8 @@ extension Product2Sequence: BidirectionalCollection extension Product2Sequence: RandomAccessCollection where Base1: RandomAccessCollection, Base2: RandomAccessCollection {} -extension Product2Sequence.Index: Hashable where Base1.Index: Hashable, Base2.Index: Hashable {} +extension Product2Sequence.Index: Hashable + where Base1.Index: Hashable, Base2.Index: Hashable {} //===----------------------------------------------------------------------===// // product(_:_:) @@ -482,5 +484,5 @@ extension Product2Sequence.Index: Hashable where Base1.Index: Hashable, Base2.In public func product( _ s1: Base1, _ s2: Base2 ) -> Product2Sequence { - return Product2Sequence(s1, s2) + Product2Sequence(s1, s2) } diff --git a/Sources/Algorithms/RandomSample.swift b/Sources/Algorithms/RandomSample.swift index 6542476..933269d 100644 --- a/Sources/Algorithms/RandomSample.swift +++ b/Sources/Algorithms/RandomSample.swift @@ -62,8 +62,7 @@ extension Collection { /// This method is equivalent to calling `randomStableSample(k:using:)`, /// passing in the system's default random generator. /// - /// - Parameters: - /// - k: The number of elements to randomly select. + /// - Parameter k: The number of elements to randomly select. /// - Returns: An array of `k` random elements. If `k` is greater than this /// collection's count, then this method returns the full collection. /// @@ -123,12 +122,12 @@ extension Collection { // Fill the reservoir with the first `k` elements. var i = startIndex - while i < endIndex, result.count < k { + while i != endIndex, result.count < k { result.append(self[i]) formIndex(after: &i) } - while i < endIndex { + while i != endIndex { // Calculate the next value of w. w *= nextW(k: k, using: &rng) @@ -136,7 +135,7 @@ extension Collection { let offset = nextOffset(w: w, using: &rng) i = index(i, offsetBy: offset, limitedBy: endIndex) ?? endIndex - if i < endIndex { + if i != endIndex { // Swap selected element with a randomly chosen one in the reservoir. let j = Int.random(in: 0..( _ initial: Result, _ transform: @escaping (Result, Element) -> Result - ) -> ExclusiveReductionsSequence { - return reductions(into: initial) { result, element in + ) -> ExclusiveReductionsSequence { + reductions(into: initial) { result, element in result = transform(result, element) } } @@ -60,7 +59,7 @@ extension LazySequenceProtocol { /// - Parameters: /// - initial: The value to use as the initial value. /// - transform: A closure that combines the previously reduced result and - /// the next element in the receiving sequence. + /// the next element in the receiving sequence. /// - Returns: A sequence of the initial value followed by the reduced /// elements. /// @@ -69,13 +68,15 @@ extension LazySequenceProtocol { public func reductions( into initial: Result, _ transform: @escaping (inout Result, Element) -> Void - ) -> ExclusiveReductionsSequence { - ExclusiveReductionsSequence(base: self, initial: initial, transform: transform) + ) -> ExclusiveReductionsSequence { + ExclusiveReductionsSequence( + base: elements, + initial: initial, + transform: transform) } } extension Sequence { - /// Returns an array containing the accumulated results of combining the /// elements of the sequence using the given closure. /// @@ -106,7 +107,7 @@ extension Sequence { /// - Parameters: /// - initial: The value to use as the initial value. /// - transform: A closure that combines the previously reduced result and - /// the next element in the receiving sequence. + /// the next element in the receiving sequence. /// - Returns: An array of the initial value followed by the reduced elements. /// /// - Complexity: O(_n_), where _n_ is the length of the sequence. @@ -115,7 +116,7 @@ extension Sequence { _ initial: Result, _ transform: (Result, Element) throws -> Result ) rethrows -> [Result] { - return try reductions(into: initial) { result, element in + try reductions(into: initial) { result, element in result = try transform(result, element) } } @@ -150,7 +151,7 @@ extension Sequence { /// - Parameters: /// - initial: The value to use as the initial value. /// - transform: A closure that combines the previously reduced result and - /// the next element in the receiving sequence. + /// the next element in the receiving sequence. /// - Returns: An array of the initial value followed by the reduced elements. /// /// - Complexity: O(_n_), where _n_ is the length of the sequence. @@ -176,7 +177,7 @@ extension Sequence { /// A sequence of applying a transform to the element of a sequence and the /// previously transformed result. -public struct ExclusiveReductionsSequence { +public struct ExclusiveReductionsSequence { @usableFromInline internal let base: Base @@ -234,58 +235,82 @@ extension ExclusiveReductionsSequence: Sequence { @inlinable public func makeIterator() -> Iterator { - Iterator(iterator: base.makeIterator(), - current: initial, - transform: transform) + Iterator( + iterator: base.makeIterator(), + current: initial, + transform: transform) } } extension ExclusiveReductionsSequence: Collection where Base: Collection { public struct Index: Comparable { @usableFromInline - internal let representation: ReductionsIndexRepresentation + internal enum Representation { + case base(Base.Index, Result) + case end + } + + @usableFromInline + internal let representation: Representation @inlinable - internal init( - _ representation: ReductionsIndexRepresentation - ) { + internal init(_ representation: Representation) { self.representation = representation } - + + @inlinable + public static func == (lhs: Self, rhs: Self) -> Bool { + switch (lhs.representation, rhs.representation) { + case (.base(let lhs, _), .base(let rhs, _)): + return lhs == rhs + case (.end, .end): + return true + case (.base, .end), (.end, .base): + return false + } + } + @inlinable public static func < (lhs: Self, rhs: Self) -> Bool { - lhs.representation < rhs.representation + switch (lhs.representation, rhs.representation) { + case (.end, _): + return false + case (_, .end): + return true + case (.base(let lhs, _), .base(let rhs, _)): + return lhs < rhs + } } } @inlinable - public var startIndex: Index { Index(.start) } + public var startIndex: Index { + Index(.base(base.startIndex, initial)) + } @inlinable - public var endIndex: Index { Index(.end) } + public var endIndex: Index { + Index(.end) + } @inlinable public subscript(position: Index) -> Result { switch position.representation { - case .start: return initial - case .base(_, let result): return result - case .end: fatalError("Cannot get element of end index.") + case .base(_, let result): + return result + case .end: + fatalError("Cannot get element of end index.") } } @inlinable - public func index(after i: Index) -> Index { - func index(base index: Base.Index, previous: Result) -> Index { - guard index != base.endIndex else { return endIndex } - var previous = previous - transform(&previous, base[index]) - return Index(.base(index: index, result: previous)) - } - switch i.representation { - case .start: - return index(base: base.startIndex, previous: initial) - case let .base(i, result): - return index(base: base.index(after: i), previous: result) + public func index(after index: Index) -> Index { + switch index.representation { + case .base(base.endIndex, _): + return Index(.end) + case .base(let index, var result): + transform(&result, base[index]) + return Index(.base(base.index(after: index), result)) case .end: fatalError("Cannot get index after end index.") } @@ -294,38 +319,40 @@ extension ExclusiveReductionsSequence: Collection where Base: Collection { @inlinable public func distance(from start: Index, to end: Index) -> Int { switch (start.representation, end.representation) { - case (.start, .start): - return 0 - case let (.start, .base(index, _)): - return base.distance(from: base.startIndex, to: index) + 1 - case (.start, .end): - return base.distance(from: base.startIndex, to: base.endIndex) + 1 - case let (.base(index, _), .start): - return base.distance(from: index, to: base.startIndex) - 1 case let (.base(start, _), .base(end, _)): return base.distance(from: start, to: end) case let (.base(index, _), .end): - return base.distance(from: index, to: base.endIndex) - case (.end, .start): - return base.distance(from: base.endIndex, to: base.startIndex) - 1 + return base.distance(from: index, to: base.endIndex) + 1 case let (.end, .base(index, _)): - return base.distance(from: base.endIndex, to: index) + return base.distance(from: base.endIndex, to: index) - 1 case (.end, .end): return 0 } } } -extension ExclusiveReductionsSequence: LazySequenceProtocol - where Base: LazySequenceProtocol {} +extension ExclusiveReductionsSequence: LazySequenceProtocol {} extension ExclusiveReductionsSequence: LazyCollectionProtocol - where Base: LazyCollectionProtocol {} + where Base: Collection {} + +extension ExclusiveReductionsSequence.Index: Hashable + where Base.Index: Hashable +{ + @inlinable + public func hash(into hasher: inout Hasher) { + switch representation { + case .base(let base, _): + hasher.combine(base) + case .end: + break + } + } +} // MARK: - Inclusive Reductions extension LazySequenceProtocol { - /// Returns a sequence containing the accumulated results of combining the /// elements of the sequence using the given closure. /// @@ -339,22 +366,20 @@ extension LazySequenceProtocol { /// // prints [1, 3, 6, 10] /// ``` /// - /// - Parameters: - /// - transform: A closure that combines the previously reduced result and - /// the next element in the receiving sequence. + /// - Parameter transform: A closure that combines the previously reduced + /// result and the next element in the receiving sequence. /// - Returns: A sequence of the reduced elements. /// /// - Complexity: O(1) @inlinable public func reductions( _ transform: @escaping (Element, Element) -> Element - ) -> InclusiveReductionsSequence { - InclusiveReductionsSequence(base: self, transform: transform) + ) -> InclusiveReductionsSequence { + InclusiveReductionsSequence(base: elements, transform: transform) } } extension Sequence { - /// Returns an array containing the accumulated results of combining the /// elements of the sequence using the given closure. /// @@ -384,9 +409,8 @@ extension Sequence { /// If the sequence has one element, `transform` is never executed and /// an array containing only that first element is returned. /// - /// - Parameters: - /// - transform: A closure that combines the previously reduced result and - /// the next element in the receiving sequence. + /// - Parameter transform: A closure that combines the previously reduced + /// result and the next element in the receiving sequence. /// - Returns: An array of the reduced elements. /// /// - Complexity: O(_n_), where _n_ is the length of the sequence. @@ -431,11 +455,9 @@ extension InclusiveReductionsSequence: Sequence { @inlinable internal init( iterator: Base.Iterator, - element: Base.Element? = nil, transform: @escaping (Base.Element, Base.Element) -> Base.Element ) { self.iterator = iterator - self.element = element self.transform = transform } @@ -453,139 +475,97 @@ extension InclusiveReductionsSequence: Sequence { @inlinable public func makeIterator() -> Iterator { - Iterator(iterator: base.makeIterator(), - transform: transform) + Iterator(iterator: base.makeIterator(), transform: transform) } } extension InclusiveReductionsSequence: Collection where Base: Collection { public struct Index: Comparable { @usableFromInline - internal let representation: ReductionsIndexRepresentation + internal let base: Base.Index + + @usableFromInline + internal let result: Element? @inlinable - internal init( - _ representation: ReductionsIndexRepresentation - ) { - self.representation = representation + internal init(base: Base.Index, result: Element?) { + self.base = base + self.result = result } @inlinable public static func < (lhs: Self, rhs: Self) -> Bool { - lhs.representation < rhs.representation + lhs.base < rhs.base + } + + @inlinable + public static func == (lhs: Self, rhs: Self) -> Bool { + lhs.base == rhs.base } } @inlinable public var startIndex: Index { - guard base.startIndex != base.endIndex else { return endIndex } - return Index(.start) + Index(base: base.startIndex, result: base.first) } @inlinable - public var endIndex: Index { Index(.end) } - - @inlinable - public subscript(position: Index) -> Base.Element { - switch position.representation { - case .start: return base[base.startIndex] - case .base(_, let result): return result - case .end: fatalError("Cannot get element of end index.") - } + public var endIndex: Index { + Index(base: base.endIndex, result: nil) } @inlinable - public func index(after i: Index) -> Index { - func index(after i: Base.Index, previous: Base.Element) -> Index { - let index = base.index(after: i) - guard index != base.endIndex else { return endIndex } - return Index(.base(index: index, result: transform(previous, base[index]))) + public subscript(index: Index) -> Base.Element { + guard let result = index.result else { + fatalError("Can't subscript using endIndex") } - switch i.representation { - case .start: - return index(after: base.startIndex, previous: base[base.startIndex]) - case let .base(i, element): - return index(after: i, previous: element) - case .end: - fatalError("Cannot get index after end index.") + + return result + } + + @inlinable + public func index(after index: Index) -> Index { + guard let result = index.result else { + fatalError("Can't advance past endIndex") } + + let index = base.index(after: index.base) + let nextResult = index == base.endIndex + ? nil + : transform(result, base[index]) + + return Index(base: index, result: nextResult) } @inlinable public func distance(from start: Index, to end: Index) -> Int { - switch (start.representation, end.representation) { - case (.start, .start): - return 0 - case let (.start, .base(index, _)): - return base.distance(from: base.startIndex, to: index) - case (.start, .end): - return base.distance(from: base.startIndex, to: base.endIndex) - case let (.base(index, _), .start): - return base.distance(from: index, to: base.startIndex) - case let (.base(start, _), .base(end, _)): - return base.distance(from: start, to: end) - case let (.base(index, _), .end): - return base.distance(from: index, to: base.endIndex) - case (.end, .start): - return base.distance(from: base.endIndex, to: base.startIndex) - case let (.end, .base(index, _)): - return base.distance(from: base.endIndex, to: index) - case (.end, .end): - return 0 - } + base.distance(from: start.base, to: end.base) } } -extension InclusiveReductionsSequence: LazySequenceProtocol - where Base: LazySequenceProtocol {} +extension InclusiveReductionsSequence: LazySequenceProtocol {} extension InclusiveReductionsSequence: LazyCollectionProtocol - where Base: LazyCollectionProtocol {} + where Base: Collection {} -// MARK: - ReductionsIndexRepresentation - -@usableFromInline -enum ReductionsIndexRepresentation { - case start - case base(index: BaseIndex, result: Result) - case end -} - -extension ReductionsIndexRepresentation: Equatable { +extension InclusiveReductionsSequence.Index: Hashable + where Base.Index: Hashable +{ @inlinable - static func == (lhs: Self, rhs: Self) -> Bool { - switch (lhs, rhs) { - case (.start, .start): return true - case (.end, .end): return true - case let (.base(lhs, _), .base(rhs, _)): return lhs == rhs - default: return false - } - } -} - -extension ReductionsIndexRepresentation: Comparable { - @inlinable - static func < (lhs: Self, rhs: Self) -> Bool { - switch (lhs, rhs) { - case (_, .start): return false - case (.start, _): return true - case (.end, _): return false - case (_, .end): return true - case let (.base(lhs, _), .base(rhs, _)): return lhs < rhs - } + public func hash(into hasher: inout Hasher) { + hasher.combine(base) } } // MARK: - Scan extension LazySequenceProtocol { - @available(*, deprecated, message: "Use reductions(_:_:) instead.") @inlinable public func scan( _ initial: Result, _ transform: @escaping (Result, Element) -> Result - ) -> ExclusiveReductionsSequence { + ) -> ExclusiveReductionsSequence { reductions(initial, transform) } @@ -594,13 +574,12 @@ extension LazySequenceProtocol { public func scan( into initial: Result, _ transform: @escaping (inout Result, Element) -> Void - ) -> ExclusiveReductionsSequence { + ) -> ExclusiveReductionsSequence { reductions(into: initial, transform) } } extension Sequence { - @available(*, deprecated, message: "Use reductions(_:_:) instead.") @inlinable public func scan( @@ -621,18 +600,16 @@ extension Sequence { } extension LazySequenceProtocol { - @available(*, deprecated, message: "Use reductions(_:) instead.") @inlinable public func scan( _ transform: @escaping (Element, Element) -> Element - ) -> InclusiveReductionsSequence { + ) -> InclusiveReductionsSequence { reductions(transform) } } extension Sequence { - @available(*, deprecated, message: "Use reductions(_:) instead.") @inlinable public func scan( diff --git a/Sources/Algorithms/Rotate.swift b/Sources/Algorithms/Rotate.swift index 094b1d9..852939b 100644 --- a/Sources/Algorithms/Rotate.swift +++ b/Sources/Algorithms/Rotate.swift @@ -75,8 +75,8 @@ extension MutableCollection where Self: BidirectionalCollection { extension MutableCollection { /// Swaps the elements of the two given subranges, up to the upper bound of - /// the smaller subrange. The returned indices are the ends of the two - /// ranges that were actually swapped. + /// the smaller subrange. The returned indices are the ends of the two ranges + /// that were actually swapped. /// /// Input: /// [a b c d e f g h i j k l m n o p] @@ -112,8 +112,8 @@ extension MutableCollection { return (p, q) } - /// Rotates the elements within the given subrange so that the element - /// at the specified index becomes the start of the subrange. + /// Rotates the elements within the given subrange so that the element at the + /// specified index becomes the start of the subrange. /// /// Rotating a collection is equivalent to breaking the collection into two /// sections at the index `newStart`, and then swapping those two sections. @@ -146,10 +146,9 @@ extension MutableCollection { if s == m { return e } if m == e { return s } - // We have two regions of possibly-unequal length that need to be - // exchanged. The return value of this method is going to be the - // position following that of the element that is currently last - // (element j). + // We have two regions of possibly-unequal length that need to be exchanged. + // The return value of this method is going to be the position following + // that of the element that is currently last (element j). // // [a b c d e f g|h i j] or [a b c|d e f g h i j] // ^ ^ ^ ^ ^ ^ @@ -157,8 +156,8 @@ extension MutableCollection { // var ret = e // start with a known incorrect result. while true { - // Exchange the leading elements of each region (up to the - // length of the shorter region). + // Exchange the leading elements of each region (up to the length of the + // shorter region). // // [a b c d e f g|h i j] or [a b c|d e f g h i j] // ^^^^^ ^^^^^ ^^^^^ ^^^^^ @@ -169,21 +168,20 @@ extension MutableCollection { let (s1, m1) = _swapNonemptySubrangePrefixes(s.. { } } -extension SplitSequence { +extension SplitSequence: Sequence { public struct Iterator { public typealias Element = [Base.Element] @@ -85,6 +85,16 @@ extension SplitSequence { self.omittingEmptySubsequences = omittingEmptySubsequences } } + + @inlinable + public func makeIterator() -> Iterator { + Iterator( + base: base.makeIterator(), + whereSeparator: self.isSeparator, + maxSplits: self.maxSplits, + omittingEmptySubsequences: self.omittingEmptySubsequences + ) + } } extension SplitSequence.Iterator: IteratorProtocol { @@ -128,17 +138,7 @@ extension SplitSequence.Iterator: IteratorProtocol { } } -extension SplitSequence: LazySequenceProtocol { - @inlinable - public func makeIterator() -> Iterator { - return Iterator( - base: base.makeIterator(), - whereSeparator: self.isSeparator, - maxSplits: self.maxSplits, - omittingEmptySubsequences: self.omittingEmptySubsequences - ) - } -} +extension SplitSequence: LazySequenceProtocol {} extension LazySequenceProtocol { /// Lazily returns the longest possible subsequences of the sequence, in @@ -333,7 +333,7 @@ extension LazySequenceProtocol where Element: Equatable { } //===----------------------------------------------------------------------===// -// LazySplitCollection +// SplitCollection //===----------------------------------------------------------------------===// /// A collection that lazily splits a base collection into subsequences /// separated by elements that satisfy the given `whereSeparator` predicate. @@ -343,7 +343,7 @@ extension LazySequenceProtocol where Element: Equatable { /// x.split(maxSplits:omittingEmptySubsequences:whereSeparator) /// x.split(separator:maxSplits:omittingEmptySubsequences) /// -/// where `x` conforms to `LazyCollectionProtocol`. +/// where `x` conforms to `LazySequenceProtocol` and `Collection`. public struct SplitCollection { @usableFromInline internal let base: Base @@ -398,7 +398,7 @@ public struct SplitCollection { } } -extension SplitCollection: LazyCollectionProtocol { +extension SplitCollection: Collection { /// Position of a subsequence in a split collection. public struct Index: Comparable { /// The range corresponding to the subsequence at this position. @@ -475,7 +475,7 @@ extension SplitCollection: LazyCollectionProtocol { } var updatedSplitCount = splitCount - if end < base.endIndex { + if end != base.endIndex { // This subsequence ends on a separator (and perhaps includes other // separators, if we're omitting empty subsequences), so we've performed // another split. @@ -548,12 +548,15 @@ extension SplitCollection: LazyCollectionProtocol { } extension SplitCollection.Index: Hashable { + @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(sequenceLength) } } -extension LazyCollectionProtocol { +extension SplitCollection: LazyCollectionProtocol {} + +extension LazySequenceProtocol where Self: Collection, Elements: Collection { /// Lazily returns the longest possible subsequences of the collection, in /// order, that don't contain elements satisfying the given predicate. /// @@ -653,8 +656,9 @@ extension LazyCollectionProtocol { } } -extension LazyCollectionProtocol -where Element: Equatable { +extension LazySequenceProtocol + where Self: Collection, Elements: Collection, Element: Equatable +{ /// Lazily returns the longest possible subsequences of the collection, in /// order, around elements equal to the given element. /// diff --git a/Sources/Algorithms/Stride.swift b/Sources/Algorithms/Stride.swift index e1223d1..dcb4170 100644 --- a/Sources/Algorithms/Stride.swift +++ b/Sources/Algorithms/Stride.swift @@ -14,18 +14,18 @@ //===----------------------------------------------------------------------===// extension Sequence { - /// Returns a sequence stepping through the elements every `step` starting - /// at the first value. Any remainders of the stride will be trimmed. + /// Returns a sequence stepping through the elements every `step` starting at + /// the first value. Any remainders of the stride will be trimmed. /// /// (0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10] /// (0...10).striding(by: 3) // == [0, 3, 6, 9] /// - /// - Complexity: O(1). Access to successive values is O(k) where - /// _k_ is the striding `step`. + /// - Complexity: O(1). Access to successive values is O(k) where _k_ is the + /// striding `step`. /// /// - Parameter step: The amount to step with each iteration. - /// - Returns: Returns a sequence for stepping through the - /// elements by the specified amount. + /// - Returns: Returns a sequence for stepping through the elements by the + /// specified amount. @inlinable public func striding(by step: Int) -> StridingSequence { StridingSequence(base: self, stride: step) @@ -33,19 +33,19 @@ extension Sequence { } extension Collection { - /// Returns a sequence stepping through the elements every `step` starting - /// at the first value. Any remainders of the stride will be trimmed. + /// Returns a sequence stepping through the elements every `step` starting at + /// the first value. Any remainders of the stride will be trimmed. /// /// (0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10] /// (0...10).striding(by: 3) // == [0, 3, 6, 9] /// - /// - Complexity: O(1). Access to successive values is O(1) if the - /// collection conforms to `RandomAccessCollection`; otherwise, - /// O(_k_), where _k_ is the striding `step`. + /// - Complexity: O(1). Access to successive values is O(1) if the collection + /// conforms to `RandomAccessCollection`; otherwise, O(_k_), where _k_ is + /// the striding `step`. /// /// - Parameter step: The amount to step with each iteration. - /// - Returns: Returns a collection for stepping through the - /// elements by the specified amount. + /// - Returns: Returns a collection for stepping through the elements by the + /// specified amount. @inlinable public func striding(by step: Int) -> StridingCollection { StridingCollection(base: self, stride: step) @@ -53,8 +53,7 @@ extension Collection { } /// A wrapper that strides over a base sequence. -public struct StridingSequence: Sequence { - +public struct StridingSequence { @usableFromInline internal let base: Base @@ -63,15 +62,21 @@ public struct StridingSequence: Sequence { @inlinable internal init(base: Base, stride: Int) { - precondition(stride > 0, "striding must be greater than zero") + precondition(stride > 0, "Stride must be greater than zero") self.base = base self.stride = stride } } extension StridingSequence { - - /// An iterator over a `Stride` sequence. + @inlinable + public func striding(by step: Int) -> Self { + Self(base: base, stride: stride * step) + } +} + +extension StridingSequence: Sequence { + /// An iterator over a `StridingSequence` instance. public struct Iterator: IteratorProtocol { @usableFromInline internal var iterator: Base.Iterator @@ -107,13 +112,6 @@ extension StridingSequence { } } -extension StridingSequence { - @inlinable - public func striding(by step: Int) -> Self { - Self(base: base, stride: stride * step) - } -} - /// A wrapper that strides over a base collection. public struct StridingCollection { @usableFromInline @@ -138,8 +136,7 @@ extension StridingCollection { } extension StridingCollection: Collection { - - /// A position in a `Stride` collection. + /// A position in a `StridingCollection` instance. public struct Index: Comparable { @usableFromInline internal let base: Base.Index @@ -172,7 +169,7 @@ extension StridingCollection: Collection { @inlinable public func index(after i: Index) -> Index { - precondition(i.base < base.endIndex, "Advancing past end index") + precondition(i.base != base.endIndex, "Advancing past end index") return index(i, offsetBy: 1) } @@ -255,8 +252,8 @@ extension StridingCollection: Collection { @inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index { - precondition(distance <= 0 || i.base < base.endIndex, "Advancing past end index") - precondition(distance >= 0 || i.base > base.startIndex, "Incrementing past start index") + precondition(distance <= 0 || i.base != base.endIndex, "Advancing past end index") + precondition(distance >= 0 || i.base != base.startIndex, "Incrementing past start index") let limit = distance > 0 ? endIndex : startIndex let idx = index(i, offsetBy: distance, limitedBy: limit) precondition(idx != nil, "The distance \(distance) is not valid for this collection") @@ -269,10 +266,11 @@ extension StridingCollection: BidirectionalCollection @inlinable public func index(before i: Index) -> Index { - precondition(i.base > base.startIndex, "Incrementing past start index") + precondition(i.base != base.startIndex, "Incrementing past start index") return index(i, offsetBy: -1) } } -extension StridingCollection: RandomAccessCollection where Base: RandomAccessCollection {} +extension StridingCollection: RandomAccessCollection + where Base: RandomAccessCollection {} extension StridingCollection.Index: Hashable where Base.Index: Hashable {} diff --git a/Sources/Algorithms/Suffix.swift b/Sources/Algorithms/Suffix.swift index 56966c7..c091b82 100644 --- a/Sources/Algorithms/Suffix.swift +++ b/Sources/Algorithms/Suffix.swift @@ -17,10 +17,10 @@ extension BidirectionalCollection { /// Returns a subsequence containing the elements from the end until /// `predicate` returns `false` and skipping the remaining elements. /// - /// - Parameter predicate: A closure that takes an element of the - /// sequence as its argument and returns `true` if the element should - /// be included or `false` if it should be excluded. Once the predicate - /// returns `false` it will not be called again. + /// - Parameter predicate: A closure that takes an element of the sequence as + /// its argument and returns `true` if the element should be included or + /// `false` if it should be excluded. Once the predicate returns `false` it + /// will not be called again. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable diff --git a/Sources/Algorithms/Trim.swift b/Sources/Algorithms/Trim.swift index 9771f91..832216b 100644 --- a/Sources/Algorithms/Trim.swift +++ b/Sources/Algorithms/Trim.swift @@ -13,18 +13,17 @@ //===----------------------------------------------------------------------===// extension Collection { - /// Returns a `SubSequence` formed by discarding all elements at the start - /// of the collection which satisfy the given predicate. + /// Returns a `SubSequence` formed by discarding all elements at the start of + /// the collection which satisfy the given predicate. /// - /// This example uses `trimmingPrefix(while:)` to get a substring without the white - /// space at the beginning of the string: + /// This example uses `trimmingPrefix(while:)` to get a substring without the + /// white space at the beginning of the string: /// /// let myString = " hello, world " /// print(myString.trimmingPrefix(while: \.isWhitespace)) // "hello, world " /// - /// - Parameters: - /// - predicate: A closure which determines if the element should be - /// omitted from the resulting slice. + /// - Parameter predicate: A closure which determines if the element should be + /// omitted from the resulting slice. /// /// - Complexity: O(*n*), where *n* is the length of this collection. /// @@ -33,7 +32,7 @@ extension Collection { while predicate: (Element) throws -> Bool ) rethrows -> SubSequence { let start = try endOfPrefix(while: predicate) - return self[start.. Bool ) rethrows -> SubSequence { - return try trimmingPrefix(while: predicate).trimmingSuffix(while: predicate) + try trimmingPrefix(while: predicate).trimmingSuffix(while: predicate) } - /// Returns a `SubSequence` formed by discarding all elements at the end - /// of the collection which satisfy the given predicate. + /// Returns a `SubSequence` formed by discarding all elements at the end of + /// the collection which satisfy the given predicate. /// - /// This example uses `trimmingSuffix(while:)` to get a substring without the white - /// space at the end of the string: + /// This example uses `trimmingSuffix(while:)` to get a substring without the + /// white space at the end of the string: /// /// let myString = " hello, world " /// print(myString.trimmingSuffix(while: \.isWhitespace)) // " hello, world" /// - /// - Parameters: - /// - predicate: A closure which determines if the element should be - /// omitted from the resulting slice. + /// - Parameter predicate: A closure which determines if the element should be + /// omitted from the resulting slice. /// /// - Complexity: O(*n*), where *n* is the length of this collection. /// @@ -140,7 +135,7 @@ extension BidirectionalCollection { while predicate: (Element) throws -> Bool ) rethrows -> SubSequence { let end = try startOfSuffix(while: predicate) - return self[startIndex.. Bool ) rethrows { - replaceSubrange(startIndex.. { } extension UniquedSequence: Sequence { - /// The iterator for a `Uniqued` sequence. + /// The iterator for a `UniquedSequence` instance. public struct Iterator: IteratorProtocol { @usableFromInline internal var base: Base.Iterator @@ -103,9 +103,9 @@ extension Sequence { /// // Prints '["dog", "pig", "cat", "ox"]' /// /// - Parameter projection: A closure that transforms an element into the - /// value to use for uniqueness. If `projection` returns the same value - /// for two different elements, the second element will be excluded - /// from the resulting array. + /// value to use for uniqueness. If `projection` returns the same value for + /// two different elements, the second element will be excluded from the + /// resulting array. /// /// - Returns: An array with only the unique elements of this sequence, as /// determined by the result of `projection` for each element. diff --git a/Sources/Algorithms/Windows.swift b/Sources/Algorithms/Windows.swift index 5d081a0..fc69ef6 100644 --- a/Sources/Algorithms/Windows.swift +++ b/Sources/Algorithms/Windows.swift @@ -40,7 +40,7 @@ extension Collection { /// Access to successive windows is O(1). @inlinable public func windows(ofCount count: Int) -> WindowsCollection { - WindowsCollection(base: self, size: count) + WindowsCollection(base: self, windowSize: count) } } @@ -51,23 +51,23 @@ public struct WindowsCollection { internal let base: Base @usableFromInline - internal let size: Int + internal let windowSize: Int @usableFromInline - internal var firstUpperBound: Base.Index? + internal var endOfFirstWindow: Base.Index? @inlinable - internal init(base: Base, size: Int) { - precondition(size > 0, "Windows size must be greater than zero") + internal init(base: Base, windowSize: Int) { + precondition(windowSize > 0, "Windows size must be greater than zero") self.base = base - self.size = size - self.firstUpperBound = - base.index(base.startIndex, offsetBy: size, limitedBy: base.endIndex) + self.windowSize = windowSize + self.endOfFirstWindow = + base.index(base.startIndex, offsetBy: windowSize, limitedBy: base.endIndex) } } extension WindowsCollection: Collection { - /// A position in a `Windows` collection. + /// A position in a `WindowsCollection` instance. public struct Index: Comparable { @usableFromInline internal var lowerBound: Base.Index @@ -94,7 +94,7 @@ extension WindowsCollection: Collection { @inlinable public var startIndex: Index { - if let upperBound = firstUpperBound { + if let upperBound = endOfFirstWindow { return Index(lowerBound: base.startIndex, upperBound: upperBound) } else { return endIndex @@ -116,12 +116,14 @@ extension WindowsCollection: Collection { @inlinable public func index(after index: Index) -> Index { - precondition(index < endIndex, "Advancing past end index") + precondition(index != endIndex, "Advancing past end index") guard index.upperBound < base.endIndex else { return endIndex } - return Index( - lowerBound: base.index(after: index.lowerBound), - upperBound: base.index(after: index.upperBound) - ) + + let lowerBound = windowSize == 1 + ? index.upperBound + : base.index(after: index.lowerBound) + let upperBound = base.index(after: index.upperBound) + return Index(lowerBound: lowerBound, upperBound: upperBound) } @inlinable @@ -185,7 +187,7 @@ extension WindowsCollection: Collection { // |> > >|>| or |> > >| // output: [x x x x x|x x x x x] [x x x x x x x x x x] (`endIndex`) - if distance >= size { + if distance >= windowSize { // Avoid traversing `self[i.lowerBound..= i.upperBound, let lowerBound = base.index( i.upperBound, - offsetBy: distance - size, + offsetBy: distance - windowSize, limitedBy: limit.lowerBound), let indexBeforeUpperBound = base.index( lowerBound, - offsetBy: size - 1, + offsetBy: windowSize - 1, limitedBy: limit.upperBound) else { return nil } @@ -262,9 +264,9 @@ extension WindowsCollection: Collection { else { return nil } return Index( - lowerBound: base.index(upperBound, offsetBy: -size), + lowerBound: base.index(upperBound, offsetBy: -windowSize), upperBound: upperBound) - } else if distance >= size { + } else if distance >= windowSize { // Avoid traversing `self[i.lowerBound.. Int { guard start <= end else { return -distance(from: end, to: start) } guard start != end else { return 0 } - guard end < endIndex else { + guard end != endIndex else { // We add 1 here because the index before `endIndex` also has // `base.endIndex` as its upper bound. return base[start.upperBound...].count + 1 @@ -318,7 +320,7 @@ extension WindowsCollection: Collection { // |- - - -|> >| // end: [x x x x x x x|x x x x|x] - return size + base[start.upperBound.. > > >| @@ -329,13 +331,15 @@ extension WindowsCollection: Collection { } } -extension WindowsCollection: 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") + precondition(index != startIndex, "Incrementing past start index") if index == endIndex { return Index( - lowerBound: base.index(index.lowerBound, offsetBy: -size), + lowerBound: base.index(index.lowerBound, offsetBy: -windowSize), upperBound: index.upperBound ) } else { @@ -347,7 +351,10 @@ extension WindowsCollection: BidirectionalCollection where Base: BidirectionalCo } } -extension WindowsCollection: LazySequenceProtocol where Base: LazySequenceProtocol {} -extension WindowsCollection: LazyCollectionProtocol where Base: LazyCollectionProtocol {} -extension WindowsCollection: RandomAccessCollection where Base: RandomAccessCollection {} +extension WindowsCollection: RandomAccessCollection + where Base: RandomAccessCollection {} + +extension WindowsCollection: LazySequenceProtocol, LazyCollectionProtocol + where Base: LazySequenceProtocol {} + extension WindowsCollection.Index: Hashable where Base.Index: Hashable {} diff --git a/Tests/SwiftAlgorithmsTests/ReductionsTests.swift b/Tests/SwiftAlgorithmsTests/ReductionsTests.swift index f3490cc..2b5b379 100644 --- a/Tests/SwiftAlgorithmsTests/ReductionsTests.swift +++ b/Tests/SwiftAlgorithmsTests/ReductionsTests.swift @@ -13,7 +13,6 @@ import XCTest import Algorithms final class ReductionsTests: XCTestCase { - struct TestError: Error {} // MARK: - Exclusive Reductions diff --git a/Tests/SwiftAlgorithmsTests/LazySplitTests.swift b/Tests/SwiftAlgorithmsTests/SplitTests.swift similarity index 99% rename from Tests/SwiftAlgorithmsTests/LazySplitTests.swift rename to Tests/SwiftAlgorithmsTests/SplitTests.swift index 34cdfe7..f0adad5 100644 --- a/Tests/SwiftAlgorithmsTests/LazySplitTests.swift +++ b/Tests/SwiftAlgorithmsTests/SplitTests.swift @@ -13,10 +13,10 @@ import Algorithms import XCTest //===----------------------------------------------------------------------===// -// Tests for `LazySplitSequence` and `LazySplitCollection` +// Tests for `SplitSequence` and `SplitCollection` //===----------------------------------------------------------------------===// -final class LazySplitTests: XCTestCase { +final class SplitTests: XCTestCase { func testEmpty() { Validator( subject: [], diff --git a/Tests/SwiftAlgorithmsTests/TestUtilities.swift b/Tests/SwiftAlgorithmsTests/TestUtilities.swift index 6322a99..9acc458 100644 --- a/Tests/SwiftAlgorithmsTests/TestUtilities.swift +++ b/Tests/SwiftAlgorithmsTests/TestUtilities.swift @@ -59,7 +59,7 @@ extension AnyMutableCollection: MutableCollection { var endIndex: Base.Index { base.endIndex } func index(after i: Index) -> Index { - return base.index(after: i) + base.index(after: i) } subscript(position: Base.Index) -> Base.Element { @@ -180,8 +180,9 @@ func XCTAssertEqualCollections( /// independently of the `Collection` conformance, e.g. by using the /// contents of the collection directly. /// -/// - Complexity: O(*n*^3) for each collection, where *n* is the length of the -/// collection. +/// - Complexity: O(*n*^3) where *n* is the length of the collection per +/// collection if the collection conforms to `RandomAccesCollection`, +/// otherwise O(*n*^4). func validateIndexTraversals( _ collections: C..., indices: ((C) -> [C.Index])? = nil, diff --git a/Tests/SwiftAlgorithmsTests/WindowsTests.swift b/Tests/SwiftAlgorithmsTests/WindowsTests.swift index 51ce285..ae422f5 100644 --- a/Tests/SwiftAlgorithmsTests/WindowsTests.swift +++ b/Tests/SwiftAlgorithmsTests/WindowsTests.swift @@ -99,7 +99,7 @@ final class windowsTests: XCTestCase { indices: { windows in let endIndex = windows.base.endIndex let indices = windows.base.indices + [endIndex] - return zip(indices, indices.dropFirst(windows.size)) + return zip(indices, indices.dropFirst(windows.windowSize)) .map { .init(lowerBound: $0, upperBound: $1) } + [.init(lowerBound: endIndex, upperBound: endIndex)] })