Prepare for Swift Algorithms 1.0 (#167)

* Rename types to include a Sequence or Collection suffix, and clean up some guides

* Various refactors

* Replace `validateIndexTraversals` test method with `IndexValidator` type

* Add LazySequenceProtocol to StridingSequence, StridingCollection

* Update the Numerics dependency to 1.0

* Set `IndexedCollection.Indices` to `Base.Indices`

* Remove deprecations

* Update the changelog/README for the 1.0.0 release

* Fix compiler error on Linux

* Rename `WindowsCollection` to `WindowsOfCountCollection`
This commit is contained in:
Tim Vermeulen authored and GitHub committed 2021-09-09 01:01:36 +02:00
1 parent e195266e1f
commit c5ea9e3e36
61 files changed
+1608 -1273

No files matched your search

+19 -36
View File
@@ -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<Base: Sequence> {
}
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<Base: Collection> {
@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<Base>.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
+12 -26
View File
@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
/// A concatenation of two sequences with the same element type.
public struct Chain2<Base1: Sequence, Base2: Sequence>
public struct Chain2Sequence<Base1: Sequence, Base2: Sequence>
where Base1.Element == Base2.Element
{
/// The first sequence in this chain.
@@ -28,8 +28,8 @@ public struct Chain2<Base1: Sequence, Base2: Sequence>
}
}
extension Chain2: Sequence {
/// The iterator for a `Chain2` sequence.
extension Chain2Sequence: Sequence {
/// The iterator for a `Chain2Sequence` instance.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var iterator1: Base1.Iterator
@@ -38,7 +38,7 @@ extension Chain2: Sequence {
internal var iterator2: Base2.Iterator
@inlinable
internal init(_ concatenation: Chain2) {
internal init(_ concatenation: Chain2Sequence) {
iterator1 = concatenation.base1.makeIterator()
iterator2 = concatenation.base2.makeIterator()
}
@@ -55,8 +55,8 @@ extension Chain2: Sequence {
}
}
extension Chain2: Collection where Base1: Collection, Base2: Collection {
/// A position in a `Chain2` collection.
extension Chain2Sequence: Collection where Base1: Collection, Base2: Collection {
/// A position in a `Chain2Sequence` instance.
public struct Index: Comparable {
// The internal index representation, which can either be an index of the
// first collection or the second. The `endIndex` of the first collection
@@ -64,7 +64,7 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
// from the penultimate index of the first collection to the start of the
// second.
@usableFromInline
internal enum Representation : Equatable {
internal enum Representation: Equatable {
case first(Base1.Index)
case second(Base2.Index)
}
@@ -115,7 +115,7 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
@inlinable
public var endIndex: Index {
return Index(second: base2.endIndex)
Index(second: base2.endIndex)
}
@inlinable
@@ -263,7 +263,7 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
}
}
extension Chain2: BidirectionalCollection
extension Chain2Sequence: BidirectionalCollection
where Base1: BidirectionalCollection, Base2: BidirectionalCollection
{
@inlinable
@@ -280,7 +280,7 @@ extension Chain2: BidirectionalCollection
}
}
extension Chain2: RandomAccessCollection
extension Chain2Sequence: RandomAccessCollection
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
//===----------------------------------------------------------------------===//
@@ -314,20 +314,6 @@ extension Chain2: RandomAccessCollection
///
/// - Complexity: O(1)
@inlinable
public func chain<S1, S2>(_ s1: S1, _ s2: S2) -> Chain2<S1, S2> {
Chain2(base1: s1, base2: s2)
}
// MARK: - Deprecations
@available(*, deprecated, renamed: "Chain2")
public typealias Chain = Chain2
extension Sequence {
@available(*, deprecated, message: "Use the chain(_:_:) function, instead.")
public func chained<S: Sequence>(with other: S) -> Chain2<Self, S>
where Element == S.Element
{
Chain2(base1: self, base2: other)
}
public func chain<S1, S2>(_ s1: S1, _ s2: S2) -> Chain2Sequence<S1, S2> {
Chain2Sequence(base1: s1, base2: s2)
}
+84 -84
View File
@@ -13,7 +13,7 @@
/// predicate.
///
/// Call `lazy.chunked(by:)` on a collection to create an instance of this type.
public struct ChunkedBy<Base: Collection, Subject> {
public struct ChunkedByCollection<Base: Collection, Subject> {
/// The collection that this instance provides a view onto.
@usableFromInline
internal let base: Base
@@ -26,9 +26,9 @@ public struct ChunkedBy<Base: Collection, Subject> {
@usableFromInline
internal let belongInSameGroup: (Subject, Subject) -> Bool
/// The upper bound of the first chunk.
/// The end index of the first chunk.
@usableFromInline
internal var firstUpperBound: Base.Index
internal var endOfFirstChunk: Base.Index
@inlinable
internal init(
@@ -39,15 +39,15 @@ public struct ChunkedBy<Base: Collection, Subject> {
self.base = base
self.projection = projection
self.belongInSameGroup = belongInSameGroup
self.firstUpperBound = base.startIndex
self.endOfFirstChunk = base.startIndex
if !base.isEmpty {
firstUpperBound = endOfChunk(startingAt: base.startIndex)
endOfFirstChunk = endOfChunk(startingAt: base.startIndex)
}
}
}
extension ChunkedBy: LazyCollectionProtocol {
extension ChunkedByCollection: Collection {
/// A position in a chunked collection.
public struct Index: Comparable {
/// The range corresponding to the chunk at this position.
@@ -88,7 +88,7 @@ extension ChunkedBy: LazyCollectionProtocol {
@inlinable
public var startIndex: Index {
Index(base.startIndex..<firstUpperBound)
Index(base.startIndex..<endOfFirstChunk)
}
@inlinable
@@ -112,9 +112,9 @@ extension ChunkedBy: LazyCollectionProtocol {
}
}
extension ChunkedBy.Index: Hashable where Base.Index: Hashable {}
extension ChunkedByCollection.Index: Hashable where Base.Index: Hashable {}
extension ChunkedBy: BidirectionalCollection
extension ChunkedByCollection: BidirectionalCollection
where Base: BidirectionalCollection
{
/// Returns the index in the base collection of the start of the chunk ending
@@ -139,32 +139,30 @@ extension ChunkedBy: BidirectionalCollection
}
}
@available(*, deprecated, renamed: "ChunkedBy")
public typealias LazyChunked<Base: Collection, Subject> = ChunkedBy<Base, Subject>
@available(*, deprecated, renamed: "ChunkedBy")
public typealias Chunked<Base: Collection, Subject> = ChunkedBy<Base, Subject>
extension ChunkedByCollection: LazyCollectionProtocol {}
/// A collection wrapper that breaks a collection into chunks based on a
/// predicate.
///
/// Call `lazy.chunked(on:)` on a collection to create an instance of this type.
public struct ChunkedOn<Base: Collection, Subject> {
public struct ChunkedOnCollection<Base: Collection, Subject: Equatable> {
@usableFromInline
internal var chunked: ChunkedBy<Base, Subject>
internal var chunked: ChunkedByCollection<Base, Subject>
@inlinable
internal init(
base: Base,
projection: @escaping (Base.Element) -> Subject,
belongInSameGroup: @escaping (Subject, Subject) -> Bool
projection: @escaping (Base.Element) -> Subject
) {
self.chunked = ChunkedBy(base: base, projection: projection, belongInSameGroup: belongInSameGroup)
self.chunked = ChunkedByCollection(
base: base,
projection: projection,
belongInSameGroup: ==)
}
}
extension ChunkedOn: LazyCollectionProtocol {
public typealias Index = ChunkedBy<Base, Subject>.Index
extension ChunkedOnCollection: Collection {
public typealias Index = ChunkedByCollection<Base, Subject>.Index
@inlinable
public var startIndex: Index {
@@ -189,17 +187,22 @@ extension ChunkedOn: LazyCollectionProtocol {
}
}
extension ChunkedOn: BidirectionalCollection where Base: BidirectionalCollection {
extension ChunkedOnCollection: BidirectionalCollection
where Base: BidirectionalCollection
{
@inlinable
public func index(before i: Index) -> Index {
chunked.index(before: i)
}
}
extension ChunkedOnCollection: LazyCollectionProtocol {}
//===----------------------------------------------------------------------===//
// lazy.chunked(by:) / lazy.chunked(on:)
//===----------------------------------------------------------------------===//
extension LazyCollectionProtocol {
extension LazySequenceProtocol where Self: Collection, Elements: Collection {
/// Returns a lazy collection of subsequences of this collection, chunked by
/// the given predicate.
///
@@ -207,8 +210,8 @@ extension LazyCollectionProtocol {
@inlinable
public func chunked(
by belongInSameGroup: @escaping (Element, Element) -> Bool
) -> ChunkedBy<Elements, Element> {
ChunkedBy(
) -> ChunkedByCollection<Elements, Element> {
ChunkedByCollection(
base: elements,
projection: { $0 },
belongInSameGroup: belongInSameGroup)
@@ -219,13 +222,12 @@ extension LazyCollectionProtocol {
///
/// - Complexity: O(*n*), because the start index is pre-computed.
@inlinable
public func chunked<Subject: Equatable>(
public func chunked<Subject>(
on projection: @escaping (Element) -> Subject
) -> ChunkedOn<Elements, Subject> {
ChunkedOn(
) -> ChunkedOnCollection<Elements, Subject> {
ChunkedOnCollection(
base: elements,
projection: projection,
belongInSameGroup: ==)
projection: projection)
}
}
@@ -234,8 +236,8 @@ extension LazyCollectionProtocol {
//===----------------------------------------------------------------------===//
extension Collection {
/// Returns a collection of subsequences of this collection, chunked by
/// the given predicate.
/// Returns a collection of subsequences of this collection, chunked by the
/// given predicate.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
@inlinable
@@ -257,7 +259,7 @@ extension Collection {
}
if start != endIndex {
result.append(self[start..<endIndex])
result.append(self[start...])
}
return result
@@ -287,7 +289,7 @@ extension Collection {
}
if start != endIndex {
result.append((subject, self[start..<endIndex]))
result.append((subject, self[start...]))
}
return result
@@ -298,17 +300,18 @@ extension Collection {
// chunks(ofCount:)
//===----------------------------------------------------------------------===//
/// A collection that presents the elements of its base collection
/// in `SubSequence` chunks of any given count.
/// A collection that presents the elements of its base collection in
/// `SubSequence` chunks of any given count.
///
/// A `ChunkedByCount` is a lazy view on the base Collection, but it does not implicitly confer
/// laziness on algorithms applied to its result. In other words, for ordinary collections `c`:
/// A `ChunksOfCountCollection` is a lazy view on the base Collection, but it
/// does not implicitly confer laziness on algorithms applied to its result. In
/// other words, for ordinary collections `c`:
///
/// * `c.chunks(ofCount: 3)` does not create new storage
/// * `c.chunks(ofCount: 3).map(f)` maps eagerly and returns a new array
/// * `c.lazy.chunks(ofCount: 3).map(f)` maps lazily and returns a `LazyMapCollection`
public struct ChunkedByCount<Base: Collection> {
/// * `c.lazy.chunks(ofCount: 3).map(f)` maps lazily and returns a
/// `LazyMapCollection`
public struct ChunksOfCountCollection<Base: Collection> {
public typealias Element = Base.SubSequence
@usableFromInline
@@ -318,10 +321,10 @@ public struct ChunkedByCount<Base: Collection> {
internal let chunkCount: Int
@usableFromInline
internal var startUpperBound: Base.Index
internal var endOfFirstChunk: Base.Index
/// Creates a view instance that presents the elements of `base`
/// in `SubSequence` chunks of the given count.
/// Creates a view instance that presents the elements of `base` in
/// `SubSequence` chunks of the given count.
///
/// - Complexity: O(*n*), because the start index is pre-computed.
@inlinable
@@ -329,16 +332,16 @@ public struct ChunkedByCount<Base: Collection> {
self.base = _base
self.chunkCount = _chunkCount
// Compute the start index upfront in order to make
// start index a O(1) lookup.
self.startUpperBound = _base.index(
// Compute the start index upfront in order to make start index a O(1)
// lookup.
self.endOfFirstChunk = _base.index(
_base.startIndex, offsetBy: _chunkCount,
limitedBy: _base.endIndex
) ?? _base.endIndex
}
}
extension ChunkedByCount: Collection {
extension ChunksOfCountCollection: Collection {
public struct Index {
@usableFromInline
internal let baseRange: Range<Base.Index>
@@ -352,8 +355,9 @@ extension ChunkedByCount: Collection {
/// - Complexity: O(1)
@inlinable
public var startIndex: Index {
Index(_baseRange: base.startIndex..<startUpperBound)
Index(_baseRange: base.startIndex..<endOfFirstChunk)
}
@inlinable
public var endIndex: Index {
Index(_baseRange: base.endIndex..<base.endIndex)
@@ -362,13 +366,13 @@ extension ChunkedByCount: Collection {
/// - Complexity: O(1)
@inlinable
public subscript(i: Index) -> Element {
precondition(i < endIndex, "Index out of range")
precondition(i != endIndex, "Index out of range")
return base[i.baseRange]
}
@inlinable
public func index(after i: Index) -> Index {
precondition(i < endIndex, "Advancing past end index")
precondition(i != endIndex, "Advancing past end index")
let baseIdx = base.index(
i.baseRange.upperBound, offsetBy: chunkCount,
limitedBy: base.endIndex
@@ -377,30 +381,30 @@ extension ChunkedByCount: Collection {
}
}
extension ChunkedByCount.Index: Comparable {
extension ChunksOfCountCollection.Index: Comparable {
@inlinable
public static func == (lhs: ChunkedByCount.Index,
rhs: ChunkedByCount.Index) -> Bool {
public static func == (lhs: ChunksOfCountCollection.Index,
rhs: ChunksOfCountCollection.Index) -> Bool {
lhs.baseRange.lowerBound == rhs.baseRange.lowerBound
}
@inlinable
public static func < (lhs: ChunkedByCount.Index,
rhs: ChunkedByCount.Index) -> Bool {
public static func < (lhs: ChunksOfCountCollection.Index,
rhs: ChunksOfCountCollection.Index) -> Bool {
lhs.baseRange.lowerBound < rhs.baseRange.lowerBound
}
}
extension ChunkedByCount:
extension ChunksOfCountCollection:
BidirectionalCollection, RandomAccessCollection
where Base: RandomAccessCollection {
@inlinable
public func index(before i: Index) -> Index {
precondition(i > startIndex, "Advancing past start index")
precondition(i != startIndex, "Advancing past start index")
var offset = chunkCount
if i.baseRange.lowerBound == base.endIndex {
let remainder = base.count%chunkCount
let remainder = base.count % chunkCount
if remainder != 0 {
offset = remainder
}
@@ -414,7 +418,7 @@ where Base: RandomAccessCollection {
}
}
extension ChunkedByCount {
extension ChunksOfCountCollection {
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
let distance =
@@ -485,9 +489,9 @@ extension ChunkedByCount {
let remainder = base.count%chunkCount
// We have to take it into account when calculating offsets.
if remainder != 0 {
// Distance "minus" one(at this point distance is negative)
// because we need to adjust for the last position that have
// a variadic(remainder) number of elements.
// Distance "minus" one(at this point distance is negative) because we
// need to adjust for the last position that have a variadic(remainder)
// number of elements.
return ((distance + 1) * chunkCount) - remainder
}
}
@@ -521,14 +525,13 @@ extension ChunkedByCount {
if let limit = limit {
if baseIdx == nil {
// If we past the bounds while advancing forward and the
// limit is the `endIndex`, since the computation on base
// don't take into account the remainder, we have to make
// sure that passing the bound was because of the distance
// not just because of a remainder. Special casing is less
// expensive than always use count(which could be O(n) for
// non-random access collection base) to compute the base
// distance taking remainder into account.
// If we past the bounds while advancing forward and the limit is the
// `endIndex`, since the computation on base don't take into account the
// remainder, we have to make sure that passing the bound was because of
// the distance not just because of a remainder. Special casing is less
// expensive than always use count(which could be O(n) for non-random
// access collection base) to compute the base distance taking remainder
// into account.
if baseDistance > 0 && limit == endIndex {
if self.distance(from: i, to: limit) < distance {
return nil
@@ -555,13 +558,13 @@ extension ChunkedByCount {
}
extension Collection {
/// Returns a `ChunkedCollection<Self>` view presenting the elements
/// in chunks with count of the given count parameter.
/// Returns a `ChunksOfCountCollection<Self>` view presenting the elements in
/// chunks with count of the given count parameter.
///
/// - Parameter size: The size of the chunks. If the count parameter
/// is evenly divided by the count of the base `Collection` all the
/// chunks will have the count equals to size.
/// Otherwise, the last chunk will contain the remaining elements.
/// - Parameter count: The size of the chunks. If the count parameter is
/// evenly divided by the count of the base `Collection` all the chunks will
/// have the count equals to size. Otherwise, the last chunk will contain
/// the remaining elements.
///
/// let c = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
/// print(c.chunks(ofCount: 5).map(Array.init))
@@ -572,16 +575,13 @@ extension Collection {
///
/// - Complexity: O(*n*), because the start index is pre-computed.
@inlinable
public func chunks(ofCount count: Int) -> ChunkedByCount<Self> {
public func chunks(ofCount count: Int) -> ChunksOfCountCollection<Self> {
precondition(count > 0, "Cannot chunk with count <= 0!")
return ChunkedByCount(_base: self, _chunkCount: count)
return ChunksOfCountCollection(_base: self, _chunkCount: count)
}
}
extension ChunkedByCount.Index: Hashable where Base.Index: Hashable {}
extension ChunksOfCountCollection.Index: Hashable where Base.Index: Hashable {}
// Lazy conditional conformance.
extension ChunkedByCount: LazySequenceProtocol
extension ChunksOfCountCollection: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazySequenceProtocol {}
extension ChunkedByCount: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
+24 -17
View File
@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
/// A collection wrapper that generates combinations of a base collection.
public struct Combinations<Base: Collection> {
public struct CombinationsSequence<Base: Collection> {
/// The collection to iterate over for combinations.
@usableFromInline
internal let base: Base
@@ -19,12 +19,15 @@ public struct Combinations<Base: Collection> {
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<Int>?
/// Initializes a `Combinations` for all combinations of `base` of size `k`.
/// Initializes a `CombinationsSequence` for all combinations of `base` of
/// size `k`.
///
/// - Parameters:
/// - base: The collection to iterate over for combinations.
/// - k: The expected size of each combination.
@@ -33,8 +36,9 @@ public struct Combinations<Base: Collection> {
self.init(base, kRange: k...k)
}
/// Initializes a `Combinations` for all combinations of `base` of sizes
/// within a given range.
/// Initializes a `CombinationsSequence` for all combinations of `base` of
/// sizes within a given range.
///
/// - Parameters:
/// - base: The collection to iterate over for combinations.
/// - kRange: The range of accepted sizes of combinations.
@@ -76,13 +80,14 @@ public struct Combinations<Base: Collection> {
}
}
extension Combinations: Sequence {
/// The iterator for a `Combinations` instance.
extension CombinationsSequence: Sequence {
/// The iterator for a `CombinationsSequence` instance.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal let base: Base
/// The current range of accepted sizes of combinations.
///
/// - Note: The range is contracted until empty while iterating over
/// combinations of different sizes. When the range is empty, iteration is
/// finished.
@@ -99,7 +104,7 @@ extension Combinations: Sequence {
internal var indexes: [Base.Index]
@inlinable
internal init(_ combinations: Combinations) {
internal init(_ combinations: CombinationsSequence) {
self.base = combinations.base
self.kRange = combinations.kRange ?? 0..<0
self.indexes = Array(combinations.base.indices.prefix(kRange.lowerBound))
@@ -175,12 +180,14 @@ extension Combinations: Sequence {
}
}
@inlinable
public func makeIterator() -> Iterator {
Iterator(self)
}
}
extension Combinations: LazySequenceProtocol where Base: LazySequenceProtocol {}
extension CombinationsSequence: LazySequenceProtocol
where Base: LazySequenceProtocol {}
//===----------------------------------------------------------------------===//
// combinations(ofCount:)
@@ -243,16 +250,16 @@ extension Collection {
/// limited range is empty, the resulting sequence has no elements.
///
/// - Parameter kRange: The range of numbers of elements to include in each
/// combination.
/// combination.
///
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
/// is the number of elements in the base collection, since `Combinations`
/// accesses the `count` of the base collection.
/// is the number of elements in the base collection, since
/// `CombinationsSequence` accesses the `count` of the base collection.
@inlinable
public func combinations<R: RangeExpression>(
ofCount kRange: R
) -> Combinations<Self> where R.Bound == Int {
return Combinations(self, kRange: kRange)
) -> CombinationsSequence<Self> where R.Bound == Int {
CombinationsSequence(self, kRange: kRange)
}
/// Returns a collection of combinations of this collection's elements, with
@@ -282,11 +289,11 @@ extension Collection {
/// - Parameter k: The number of elements to include in each combination.
///
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
/// is the number of elements in the base collection, since `Combinations`
/// accesses the `count` of the base collection.
/// is the number of elements in the base collection, since
/// `CombinationsSequence` accesses the `count` of the base collection.
@inlinable
public func combinations(ofCount k: Int) -> Combinations<Self> {
public func combinations(ofCount k: Int) -> CombinationsSequence<Self> {
precondition(k >= 0, "Can't have combinations with a negative number of elements.")
return Combinations(self, k: k)
return CombinationsSequence(self, k: k)
}
}
+16 -13
View File
@@ -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<Base: Sequence, Element>: Sequence
where Base.Element == Element? {
@@ -42,14 +43,15 @@ public struct CompactedSequence<Base: Sequence, Element>: 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<Base: Collection, Element>: 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<Unwrapped>() -> CompactedCollection<Self, Unwrapped>
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 {}
+28 -28
View File
@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
/// A collection wrapper that repeats the elements of a base collection.
public struct Cycle<Base: Collection> {
public struct CycledSequence<Base: Collection> {
/// The collection to repeat.
@usableFromInline
internal let base: Base
@@ -21,8 +21,8 @@ public struct Cycle<Base: Collection> {
}
}
extension Cycle: Sequence {
/// The iterator for a `Cycle` sequence.
extension CycledSequence: Sequence {
/// The iterator for a `CycledSequence` instance.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal let base: Base
@@ -55,36 +55,33 @@ extension Cycle: Sequence {
}
}
extension Cycle: LazySequenceProtocol where Base: LazySequenceProtocol {}
extension CycledSequence: LazySequenceProtocol
where Base: LazySequenceProtocol {}
/// A collection wrapper that repeats the elements of a base collection for a
/// finite number of times.
public struct FiniteCycle<Base: Collection> {
/// A Product2 instance for iterating the Base collection.
public struct CycledTimesCollection<Base: Collection> {
/// A `Product2Sequence` instance for iterating the base collection.
@usableFromInline
internal let product: Product2<Range<Int>, Base>
internal let product: Product2Sequence<Range<Int>, Base>
@inlinable
internal init(base: Base, times: Int) {
self.product = Product2(0..<times, base)
self.product = Product2Sequence(0..<times, base)
}
}
extension FiniteCycle: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazyCollectionProtocol { }
extension FiniteCycle: Collection {
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: Product2<Range<Int>, Base>.Index
internal let productIndex: Product2Sequence<Range<Int>, Base>.Index
@inlinable
internal init(_ productIndex: Product2<Range<Int>, Base>.Index) {
internal init(_ productIndex: Product2Sequence<Range<Int>, Base>.Index) {
self.productIndex = productIndex
}
@@ -137,11 +134,11 @@ extension FiniteCycle: Collection {
offsetBy distance: Int,
limitedBy limit: Index
) -> Index? {
guard let productIndex = product.index(i.productIndex,
offsetBy: distance,
limitedBy: limit.productIndex) else {
return nil
}
guard let productIndex = product.index(
i.productIndex,
offsetBy: distance,
limitedBy: limit.productIndex)
else { return nil }
return Index(productIndex)
}
@@ -151,7 +148,7 @@ extension FiniteCycle: Collection {
}
}
extension FiniteCycle: BidirectionalCollection
extension CycledTimesCollection: BidirectionalCollection
where Base: BidirectionalCollection {
@inlinable
public func index(before i: Index) -> Index {
@@ -160,9 +157,12 @@ extension FiniteCycle: BidirectionalCollection
}
}
extension FiniteCycle: RandomAccessCollection
extension CycledTimesCollection: RandomAccessCollection
where Base: RandomAccessCollection {}
extension CycledTimesCollection: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazySequenceProtocol {}
//===----------------------------------------------------------------------===//
// cycled()
//===----------------------------------------------------------------------===//
@@ -194,8 +194,8 @@ extension Collection {
///
/// - Complexity: O(1)
@inlinable
public func cycled() -> Cycle<Self> {
Cycle(base: self)
public func cycled() -> CycledSequence<Self> {
CycledSequence(base: self)
}
/// Returns a sequence that repeats the elements of this collection the
@@ -216,7 +216,7 @@ extension Collection {
///
/// - Complexity: O(1)
@inlinable
public func cycled(times: Int) -> FiniteCycle<Self> {
FiniteCycle(base: self, times: times)
public func cycled(times: Int) -> CycledTimesCollection<Self> {
CycledTimesCollection(base: self, times: times)
}
}
+3 -2
View File
@@ -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<Result>(
@inlinable
public func firstNonNil<Result>(
_ transform: (Element) throws -> Result?
) rethrows -> Result? {
for value in self {
+11 -6
View File
@@ -12,7 +12,9 @@
/// A collection consisting of all the elements contained in a collection of
/// collections.
@usableFromInline
internal struct FlattenCollection<Base: Collection> where Base.Element: Collection {
internal struct FlattenCollection<Base: Collection>
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..<end.outer].dropFirst()
@@ -199,7 +203,10 @@ extension FlattenCollection: Collection {
if let limitInner = limit.inner {
let element = base[outer]
return element.index(element.startIndex, offsetBy: remainder, limitedBy: limitInner)
return element.index(
element.startIndex,
offsetBy: remainder,
limitedBy: limitInner)
.map { inner in Index(outer: outer, inner: inner) }
} else {
return nil
@@ -287,10 +294,8 @@ extension FlattenCollection: BidirectionalCollection
}
}
extension FlattenCollection: LazySequenceProtocol
extension FlattenCollection: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazySequenceProtocol, Base.Element: LazySequenceProtocol {}
extension FlattenCollection: LazyCollectionProtocol
where Base: LazyCollectionProtocol, Base.Element: LazyCollectionProtocol {}
//===----------------------------------------------------------------------===//
// joined()
+25 -12
View File
@@ -11,10 +11,7 @@
/// A collection wrapper that iterates over the indices and elements of a
/// collection together.
public struct Indexed<Base: Collection> {
/// The element type for an `Indexed` collection.
public typealias Element = (index: Base.Index, element: Base.Element)
public struct IndexedCollection<Base: Collection> {
/// The base collection.
@usableFromInline
internal let base: Base
@@ -25,7 +22,10 @@ public struct Indexed<Base: Collection> {
}
}
extension Indexed: Collection {
extension IndexedCollection: Collection {
/// The element type for an `IndexedCollection` collection.
public typealias Element = (index: Base.Index, element: Base.Element)
@inlinable
public var startIndex: Base.Index {
base.startIndex
@@ -52,7 +52,11 @@ extension Indexed: Collection {
}
@inlinable
public func index(_ i: Base.Index, offsetBy distance: Int, limitedBy limit: Base.Index) -> Base.Index? {
public func index(
_ i: Base.Index,
offsetBy distance: Int,
limitedBy limit: Base.Index
) -> Base.Index? {
base.index(i, offsetBy: distance, limitedBy: limit)
}
@@ -60,18 +64,27 @@ extension Indexed: Collection {
public func distance(from start: Base.Index, to end: Base.Index) -> Int {
base.distance(from: start, to: end)
}
@inlinable
public var indices: Base.Indices {
base.indices
}
}
extension Indexed: BidirectionalCollection where Base: BidirectionalCollection {
extension IndexedCollection: BidirectionalCollection
where Base: BidirectionalCollection
{
@inlinable
public func index(before i: Base.Index) -> Base.Index {
base.index(before: i)
}
}
extension Indexed: RandomAccessCollection where Base: RandomAccessCollection {}
extension Indexed: LazySequenceProtocol where Base: LazySequenceProtocol {}
extension Indexed: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
extension IndexedCollection: RandomAccessCollection
where Base: RandomAccessCollection {}
extension IndexedCollection: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazySequenceProtocol {}
//===----------------------------------------------------------------------===//
// indexed()
@@ -94,7 +107,7 @@ extension Collection {
///
/// Returns: A collection of paired indices and elements of this collection.
@inlinable
public func indexed() -> Indexed<Self> {
Indexed(base: self)
public func indexed() -> IndexedCollection<Self> {
IndexedCollection(base: self)
}
}
+60 -44
View File
@@ -13,9 +13,9 @@
// Intersperse
//===----------------------------------------------------------------------===//
/// A sequence that presents the elements of a base sequence of elements
/// with a separator between each of those elements.
public struct Intersperse<Base: Sequence> {
/// A sequence that presents the elements of a base sequence of elements with a
/// separator between each of those elements.
public struct InterspersedSequence<Base: Sequence> {
@usableFromInline
internal let base: Base
@@ -29,9 +29,16 @@ public struct Intersperse<Base: Sequence> {
}
}
extension Intersperse: Sequence {
/// The iterator for an `Intersperse` sequence.
extension InterspersedSequence: Sequence {
/// The iterator for an `InterspersedSequence` sequence.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal enum State {
case start
case element(Base.Element)
case separator
}
@usableFromInline
internal var iterator: Base.Iterator
@@ -46,13 +53,6 @@ extension Intersperse: Sequence {
self.iterator = iterator
self.separator = separator
}
@usableFromInline
enum State {
case start
case element(Base.Element)
case separator
}
@inlinable
public mutating func next() -> Base.Element? {
@@ -76,13 +76,13 @@ extension Intersperse: Sequence {
}
@inlinable
public func makeIterator() -> Intersperse<Base>.Iterator {
public func makeIterator() -> InterspersedSequence<Base>.Iterator {
Iterator(iterator: base.makeIterator(), separator: separator)
}
}
extension Intersperse: Collection where Base: Collection {
/// A position in an `Intersperse` collection.
extension InterspersedSequence: Collection where Base: Collection {
/// A position in an `InterspersedSequence` instance.
public struct Index: Comparable {
@usableFromInline
internal enum Representation: Equatable {
@@ -256,7 +256,7 @@ extension Intersperse: Collection where Base: Collection {
}
}
extension Intersperse: BidirectionalCollection
extension InterspersedSequence: BidirectionalCollection
where Base: BidirectionalCollection
{
@inlinable
@@ -271,14 +271,14 @@ extension Intersperse: BidirectionalCollection
}
}
extension Intersperse: RandomAccessCollection
extension InterspersedSequence: RandomAccessCollection
where Base: RandomAccessCollection {}
extension Intersperse: LazySequenceProtocol
extension InterspersedSequence: LazySequenceProtocol
where Base: LazySequenceProtocol {}
extension Intersperse: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
extension InterspersedSequence: LazyCollectionProtocol
where Base: LazySequenceProtocol & Collection {}
//===----------------------------------------------------------------------===//
// InterspersedMap
@@ -289,7 +289,7 @@ extension Intersperse: LazyCollectionProtocol
/// elements, with a separator that separates each pair of adjacent transformed
/// values.
@usableFromInline
internal struct InterspersedMap<Base: Sequence, Result> {
internal struct InterspersedMapSequence<Base: Sequence, Result> {
@usableFromInline
internal let base: Base
@@ -300,9 +300,16 @@ internal struct InterspersedMap<Base: Sequence, Result> {
internal let separator: (Base.Element, Base.Element) -> Result
}
extension InterspersedMap: Sequence {
extension InterspersedMapSequence: Sequence {
@usableFromInline
internal struct Iterator: IteratorProtocol {
@usableFromInline
internal enum State {
case start
case element(Base.Element)
case separator(previous: Base.Element)
}
@usableFromInline
internal var base: Base.Iterator
@@ -325,13 +332,6 @@ extension InterspersedMap: Sequence {
self.transform = transform
self.separator = separator
}
@usableFromInline
internal enum State {
case start
case element(Base.Element)
case separator(previous: Base.Element)
}
@inlinable
internal mutating func next() -> Result? {
@@ -360,11 +360,11 @@ extension InterspersedMap: Sequence {
}
}
extension InterspersedMap: Collection where Base: Collection {
extension InterspersedMapSequence: Collection where Base: Collection {
@usableFromInline
internal struct Index: Comparable {
@usableFromInline
internal enum Representation: Equatable {
internal enum Representation {
case element(Base.Index)
case separator(previous: Base.Index, next: Base.Index)
}
@@ -561,7 +561,7 @@ extension InterspersedMap: Collection where Base: Collection {
}
}
extension InterspersedMap: BidirectionalCollection
extension InterspersedMapSequence: BidirectionalCollection
where Base: BidirectionalCollection
{
@inlinable
@@ -577,20 +577,31 @@ extension InterspersedMap: BidirectionalCollection
}
}
extension InterspersedMap.Index.Representation: Hashable
where Base.Index: Hashable {}
extension InterspersedMapSequence.Index: Hashable
where Base.Index: Hashable
{
@inlinable
internal func hash(into hasher: inout Hasher) {
switch representation {
case .element(let base):
hasher.combine(false)
hasher.combine(base)
case .separator(_, let next):
hasher.combine(true)
hasher.combine(next)
}
}
}
extension InterspersedMap: LazySequenceProtocol
where Base: LazySequenceProtocol {}
extension InterspersedMap: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
extension InterspersedMapSequence: LazySequenceProtocol {}
extension InterspersedMapSequence: LazyCollectionProtocol
where Base: Collection {}
//===----------------------------------------------------------------------===//
// interspersed(with:)
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a sequence containing elements of this sequence with the given
/// separator inserted in between each element.
///
@@ -620,13 +631,15 @@ extension Sequence {
///
/// - Complexity: O(1)
@inlinable
public func interspersed(with separator: Element) -> Intersperse<Self> {
Intersperse(base: self, separator: separator)
public func interspersed(
with separator: Element
) -> InterspersedSequence<Self> {
InterspersedSequence(base: self, separator: separator)
}
}
//===----------------------------------------------------------------------===//
// lazy.interspersed(_:with:)
// lazy.interspersedMap(_:with:)
//===----------------------------------------------------------------------===//
extension LazySequenceProtocol {
@@ -647,7 +660,10 @@ extension LazySequenceProtocol {
internal func interspersedMap<Result>(
_ transform: @escaping (Element) -> Result,
with separator: @escaping (Element, Element) -> Result
) -> InterspersedMap<Self, Result> {
InterspersedMap(base: self, transform: transform, separator: separator)
) -> InterspersedMapSequence<Elements, Result> {
InterspersedMapSequence(
base: elements,
transform: transform,
separator: separator)
}
}
+19 -25
View File
@@ -19,8 +19,8 @@ public struct JoinedBySequence<Base: Sequence, Separator: Sequence>
where Base.Element: Sequence, Base.Element.Element == Separator.Element
{
@usableFromInline
internal typealias Inner = FlattenSequence<
Intersperse<LazyMapSequence<Base, EitherSequence<Base.Element, Separator>>>>
internal typealias Inner = FlattenSequence<InterspersedSequence<
LazyMapSequence<Base, EitherSequence<Base.Element, Separator>>>>
@usableFromInline
internal let inner: Inner
@@ -70,8 +70,8 @@ public struct JoinedByClosureSequence<Base: Sequence, Separator: Sequence>
where Base.Element: Sequence, Base.Element.Element == Separator.Element
{
@usableFromInline
internal typealias Inner = FlattenSequence<
InterspersedMap<LazySequence<Base>, EitherSequence<Base.Element, Separator>>>
internal typealias Inner = FlattenSequence<InterspersedMapSequence<
Base, EitherSequence<Base.Element, Separator>>>
@usableFromInline
internal let inner: Inner
@@ -111,8 +111,7 @@ extension JoinedByClosureSequence: Sequence {
}
}
extension JoinedByClosureSequence: LazySequenceProtocol
where Base: LazySequenceProtocol {}
extension JoinedByClosureSequence: LazySequenceProtocol {}
//===----------------------------------------------------------------------===//
// JoinedByCollection
@@ -124,8 +123,8 @@ public struct JoinedByCollection<Base: Collection, Separator: Collection>
where Base.Element: Collection, Base.Element.Element == Separator.Element
{
@usableFromInline
internal typealias Inner = FlattenCollection<
Intersperse<LazyMapSequence<Base, EitherSequence<Base.Element, Separator>>>>
internal typealias Inner = FlattenCollection<InterspersedSequence<
LazyMapSequence<Base, EitherSequence<Base.Element, Separator>>>>
@usableFromInline
internal let inner: Inner
@@ -212,10 +211,8 @@ extension JoinedByCollection: BidirectionalCollection
}
}
extension JoinedByCollection: LazySequenceProtocol
extension JoinedByCollection: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazySequenceProtocol {}
extension JoinedByCollection: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
//===----------------------------------------------------------------------===//
// JoinedByClosureCollection
@@ -228,8 +225,8 @@ public struct JoinedByClosureCollection<Base: Collection, Separator: Collection>
where Base.Element: Collection, Base.Element.Element == Separator.Element
{
@usableFromInline
internal typealias Inner = FlattenCollection<
InterspersedMap<LazySequence<Base>, EitherSequence<Base.Element, Separator>>>
internal typealias Inner = FlattenCollection<InterspersedMapSequence<
Base, EitherSequence<Base.Element, Separator>>>
@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<Self, CollectionOfOne<Element.Element>> {
) -> JoinedByClosureSequence<Elements, CollectionOfOne<Element.Element>> {
joined(by: { CollectionOfOne(separator($0, $1)) })
}
@@ -429,8 +423,8 @@ extension LazySequenceProtocol where Element: Sequence {
@inlinable
public func joined<Separator>(
by separator: @escaping (Element, Element) -> Separator
) -> JoinedByClosureSequence<Self, Separator> {
JoinedByClosureSequence(base: self, separator: separator)
) -> JoinedByClosureSequence<Elements, Separator> {
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<Self, CollectionOfOne<Element.Element>> {
) -> JoinedByClosureCollection<Elements, CollectionOfOne<Element.Element>> {
joined(by: { CollectionOfOne(separator($0, $1)) })
}
@@ -489,7 +483,7 @@ extension LazyCollectionProtocol where Element: Collection {
@inlinable
public func joined<Separator>(
by separator: @escaping (Element, Element) -> Separator
) -> JoinedByClosureCollection<Self, Separator> {
JoinedByClosureCollection(base: self, separator: separator)
) -> JoinedByClosureCollection<Elements, Separator> {
JoinedByClosureCollection(base: elements, separator: separator)
}
}
+14 -14
View File
@@ -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: <)
}
}
+10 -10
View File
@@ -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<Index>,
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[..<i]` the predicate is `false`, and for every element
/// in `collection[i...]` the predicate is `true`.
/// `collection[..<i]` the predicate is `false`, and for every element in
/// `collection[i...]` the predicate is `true`.
///
/// - Parameter belongsInSecondPartition: A predicate that partitions the
/// collection.
+43 -33
View File
@@ -18,9 +18,9 @@ extension MutableCollection
{
/// Permutes this collection's elements through all the lexical orderings.
///
/// Call `nextPermutation()` repeatedly starting with the collection in
/// sorted order. When the full cycle of all permutations has been completed,
/// the collection will be back in sorted order and this method will return
/// Call `nextPermutation()` repeatedly starting with the collection in sorted
/// order. When the full cycle of all permutations has been completed, the
/// collection will be back in sorted order and this method will return
/// `false`.
///
/// - Returns: A Boolean value indicating whether the collection still has
@@ -76,7 +76,7 @@ extension MutableCollection
//===----------------------------------------------------------------------===//
/// A sequence of all the permutations of a collection's elements.
public struct Permutations<Base: Collection> {
public struct PermutationsSequence<Base: Collection> {
/// The base collection to iterate over for permutations.
@usableFromInline
internal let base: Base
@@ -85,12 +85,15 @@ public struct Permutations<Base: 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<Int>
/// Initializes a `Permutations` for all permutations of `base` of size `k`.
/// Initializes a `PermutationsSequence` for all permutations of `base` of
/// size `k`.
///
/// - Parameters:
/// - base: The collection to iterate over for permutations
/// - k: The expected size of each permutation, or `nil` (default) to
@@ -106,8 +109,9 @@ public struct Permutations<Base: Collection> {
self.init(base, kRange: kRange)
}
/// Initializes a `Permutations` for all combinations of `base` of sizes
/// within a given range.
/// Initializes a `PermutationsSequence` for all combinations of `base` of
/// sizes within a given range.
///
/// - Parameters:
/// - base: The collection to iterate over for permutations.
/// - kRange: The range of accepted sizes of permutations, or `nil` to
@@ -128,14 +132,14 @@ public struct Permutations<Base: Collection> {
/// The total number of permutations.
@inlinable
public var count: Int {
return kRange.map {
kRange.map {
stride(from: baseCount, to: baseCount - $0, by: -1).reduce(1, *)
}.reduce(0, +)
}
}
extension Permutations: Sequence {
/// The iterator for a `Permutations` instance.
extension PermutationsSequence: Sequence {
/// The iterator for a `PermutationsSequence` instance.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal let base: Base
@@ -160,7 +164,7 @@ extension Permutations: Sequence {
internal var indexes: [Base.Index]
@inlinable
internal init(_ permutations: Permutations) {
internal init(_ permutations: PermutationsSequence) {
self.base = permutations.base
self.baseCount = permutations.baseCount
self.kRange = permutations.kRange
@@ -259,7 +263,8 @@ extension Permutations: Sequence {
}
}
extension Permutations: LazySequenceProtocol where Base: LazySequenceProtocol {}
extension PermutationsSequence: LazySequenceProtocol
where Base: LazySequenceProtocol {}
//===----------------------------------------------------------------------===//
// permutations(ofCount:)
@@ -320,13 +325,13 @@ extension Collection {
/// results in an empty sequence.
///
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
/// is the number of elements in the base collection, since `Permutations`
/// accesses the `count` of the base collection.
/// is the number of elements in the base collection, since
/// `PermutationsSequence` accesses the `count` of the base collection.
@inlinable
public func permutations<R: RangeExpression>(
ofCount kRange: R
) -> Permutations<Self> where R.Bound == Int {
return Permutations(self, kRange: kRange)
) -> PermutationsSequence<Self> where R.Bound == Int {
PermutationsSequence(self, kRange: kRange)
}
/// Returns a collection of the permutations of this collection of the
@@ -376,14 +381,14 @@ extension Collection {
/// this collection, the resulting sequence is empty.
///
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
/// is the number of elements in the base collection, since `Permutations`
/// accesses the `count` of the base collection.
/// is the number of elements in the base collection, since
/// `PermutationsSequence` accesses the `count` of the base collection.
@inlinable
public func permutations(ofCount k: Int? = nil) -> Permutations<Self> {
public func permutations(ofCount k: Int? = nil) -> PermutationsSequence<Self> {
precondition(
k ?? 0 >= 0,
"Can't have permutations with a negative number of elements.")
return Permutations(self, k: k)
return PermutationsSequence(self, k: k)
}
}
@@ -394,9 +399,9 @@ extension Collection {
/// A sequence of the unique permutations of the elements of a sequence or
/// collection.
///
/// To create a `UniquePermutations` instance, call one of the
/// To create a `UniquePermutationsSequence` instance, call one of the
/// `uniquePermutations` methods on your collection.
public struct UniquePermutations<Base: Collection> {
public struct UniquePermutationsSequence<Base: Collection> {
/// The base collection to iterate over for permutations.
@usableFromInline
internal let base: Base
@@ -408,7 +413,7 @@ public struct UniquePermutations<Base: Collection> {
internal let kRange: Range<Int>
}
extension UniquePermutations where Base.Element: Hashable {
extension UniquePermutationsSequence where Base.Element: Hashable {
@inlinable
internal static func _indexes(_ base: Base) -> [Base.Index] {
let firstIndexesAndCountsByElement = Dictionary(
@@ -440,8 +445,8 @@ extension UniquePermutations where Base.Element: Hashable {
}
}
extension UniquePermutations: Sequence {
/// The iterator for a `UniquePermutations` instance.
extension UniquePermutationsSequence: Sequence {
/// The iterator for a `UniquePermutationsSequence` instance.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal let base: Base
@@ -496,7 +501,8 @@ extension UniquePermutations: Sequence {
}
}
extension UniquePermutations: LazySequenceProtocol where Base: LazySequenceProtocol {}
extension UniquePermutationsSequence: LazySequenceProtocol
where Base: LazySequenceProtocol {}
extension Collection where Element: Hashable {
/// Returns a sequence of the unique permutations of this sequence of the
@@ -537,11 +543,14 @@ extension Collection where Element: Hashable {
///
/// - Complexity: O(*n*), where *n* is the number of elements in this
/// collection.
public func uniquePermutations(ofCount k: Int? = nil) -> UniquePermutations<Self> {
@inlinable
public func uniquePermutations(ofCount k: Int? = nil)
-> UniquePermutationsSequence<Self>
{
if let k = k {
return UniquePermutations(self, k ..< (k + 1))
return UniquePermutationsSequence(self, k ..< (k + 1))
} else {
return UniquePermutations(self)
return UniquePermutationsSequence(self)
}
}
@@ -574,9 +583,10 @@ extension Collection where Element: Hashable {
///
/// - Complexity: O(*n*), where *n* is the number of elements in this
/// collection.
public func uniquePermutations<R: RangeExpression>(ofCount kRange: R) -> UniquePermutations<Self>
where R.Bound == Int
{
UniquePermutations(self, kRange)
@inlinable
public func uniquePermutations<R: RangeExpression>(
ofCount kRange: R
) -> UniquePermutationsSequence<Self> where R.Bound == Int {
UniquePermutationsSequence(self, kRange)
}
}
+14 -12
View File
@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
/// A sequence that represents the product of two sequences' elements.
public struct Product2<Base1: Sequence, Base2: Collection> {
public struct Product2Sequence<Base1: Sequence, Base2: Collection> {
/// The outer sequence in the product.
@usableFromInline
internal let base1: Base1
@@ -26,10 +26,10 @@ public struct Product2<Base1: Sequence, Base2: Collection> {
}
}
extension Product2: Sequence {
extension Product2Sequence: Sequence {
public typealias Element = (Base1.Element, Base2.Element)
/// The iterator for a `Product2` sequence.
/// The iterator for a `Product2Sequence` sequence.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var i1: Base1.Iterator
@@ -41,7 +41,7 @@ extension Product2: Sequence {
internal let base2: Base2
@inlinable
internal init(_ c: Product2) {
internal init(_ c: Product2Sequence) {
self.base2 = c.base2
self.i1 = c.base1.makeIterator()
self.i2 = c.base2.makeIterator()
@@ -83,13 +83,14 @@ extension Product2: Sequence {
}
}
@inlinable
public func makeIterator() -> Iterator {
return Iterator(self)
Iterator(self)
}
}
extension Product2: Collection where Base1: Collection {
/// The index type for a `Product2` collection.
extension Product2Sequence: Collection where Base1: Collection {
/// The index type for a `Product2Sequence` collection.
public struct Index: Comparable {
@usableFromInline
internal var i1: Base1.Index
@@ -419,7 +420,7 @@ extension Product2: Collection where Base1: Collection {
}
}
extension Product2: BidirectionalCollection
extension Product2Sequence: BidirectionalCollection
where Base1: BidirectionalCollection, Base2: BidirectionalCollection
{
@inlinable
@@ -436,10 +437,11 @@ extension Product2: BidirectionalCollection
}
}
extension Product2: RandomAccessCollection
extension Product2Sequence: RandomAccessCollection
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
extension Product2.Index: Hashable where Base1.Index: Hashable, Base2.Index: Hashable {}
extension Product2Sequence.Index: Hashable
where Base1.Index: Hashable, Base2.Index: Hashable {}
//===----------------------------------------------------------------------===//
// product(_:_:)
@@ -481,6 +483,6 @@ extension Product2.Index: Hashable where Base1.Index: Hashable, Base2.Index: Has
@inlinable
public func product<Base1: Sequence, Base2: Collection>(
_ s1: Base1, _ s2: Base2
) -> Product2<Base1, Base2> {
return Product2(s1, s2)
) -> Product2Sequence<Base1, Base2> {
Product2Sequence(s1, s2)
}
+6 -9
View File
@@ -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..<result.count, using: &rng)
result[j] = self[i]
@@ -154,8 +153,7 @@ extension Collection {
/// This method is equivalent to calling `randomSample(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. The returned elements may be
/// in any order. If `k` is greater than this collection's count, then this
/// method returns the full collection.
@@ -225,8 +223,7 @@ extension Sequence {
/// This method is equivalent to calling `randomSample(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. The returned elements may be
/// in any order. If `k` is greater than this sequence's count, then this
/// method returns the full sequence.
+141 -164
View File
@@ -12,7 +12,6 @@
// MARK: - Exclusive Reductions
extension LazySequenceProtocol {
/// Returns a sequence containing the accumulated results of combining the
/// elements of the sequence using the given closure.
///
@@ -29,17 +28,17 @@ 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.
/// elements.
///
/// - Complexity: O(1)
@inlinable
public func reductions<Result>(
_ initial: Result,
_ transform: @escaping (Result, Element) -> Result
) -> ExclusiveReductions<Result, Self> {
return reductions(into: initial) { result, element in
) -> ExclusiveReductionsSequence<Elements, Result> {
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<Result>(
into initial: Result,
_ transform: @escaping (inout Result, Element) -> Void
) -> ExclusiveReductions<Result, Self> {
ExclusiveReductions(base: self, initial: initial, transform: transform)
) -> ExclusiveReductionsSequence<Elements, Result> {
ExclusiveReductionsSequence(
base: elements,
initial: initial,
transform: transform)
}
}
extension Sequence {
/// Returns an array containing the accumulated results of combining the
/// elements of the sequence using the given closure.
///
@@ -106,7 +107,7 @@ extension Sequence {
/// - Parameters:
/// - initial: The value to use as the initial value.
/// - transform: A closure that combines the previously reduced result and
/// the next element in the receiving sequence.
/// the next element in the receiving sequence.
/// - Returns: An array of the initial value followed by the reduced elements.
///
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
@@ -115,7 +116,7 @@ extension Sequence {
_ initial: Result,
_ transform: (Result, Element) throws -> Result
) rethrows -> [Result] {
return try reductions(into: initial) { result, element in
try reductions(into: initial) { result, element in
result = try transform(result, element)
}
}
@@ -150,7 +151,7 @@ extension Sequence {
/// - Parameters:
/// - initial: The value to use as the initial value.
/// - transform: A closure that combines the previously reduced result and
/// the next element in the receiving sequence.
/// the next element in the receiving sequence.
/// - Returns: An array of the initial value followed by the reduced elements.
///
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
@@ -176,7 +177,7 @@ extension Sequence {
/// A sequence of applying a transform to the element of a sequence and the
/// previously transformed result.
public struct ExclusiveReductions<Result, Base: Sequence> {
public struct ExclusiveReductionsSequence<Base: Sequence, Result> {
@usableFromInline
internal let base: Base
@@ -198,7 +199,7 @@ public struct ExclusiveReductions<Result, Base: Sequence> {
}
}
extension ExclusiveReductions: Sequence {
extension ExclusiveReductionsSequence: Sequence {
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var iterator: Base.Iterator
@@ -234,58 +235,82 @@ extension ExclusiveReductions: Sequence {
@inlinable
public func makeIterator() -> Iterator {
Iterator(iterator: base.makeIterator(),
current: initial,
transform: transform)
Iterator(
iterator: base.makeIterator(),
current: initial,
transform: transform)
}
}
extension ExclusiveReductions: Collection where Base: Collection {
extension ExclusiveReductionsSequence: Collection where Base: Collection {
public struct Index: Comparable {
@usableFromInline
internal let representation: ReductionsIndexRepresentation<Base.Index, Result>
internal enum Representation {
case base(Base.Index, Result)
case end
}
@usableFromInline
internal let representation: Representation
@inlinable
internal init(
_ representation: ReductionsIndexRepresentation<Base.Index, Result>
) {
internal init(_ representation: Representation) {
self.representation = representation
}
@inlinable
public static func == (lhs: Self, rhs: Self) -> Bool {
switch (lhs.representation, rhs.representation) {
case (.base(let lhs, _), .base(let rhs, _)):
return lhs == rhs
case (.end, .end):
return true
case (.base, .end), (.end, .base):
return false
}
}
@inlinable
public static func < (lhs: Self, rhs: Self) -> Bool {
lhs.representation < rhs.representation
switch (lhs.representation, rhs.representation) {
case (.end, _):
return false
case (_, .end):
return true
case (.base(let lhs, _), .base(let rhs, _)):
return lhs < rhs
}
}
}
@inlinable
public var startIndex: Index { Index(.start) }
public var startIndex: Index {
Index(.base(base.startIndex, initial))
}
@inlinable
public var endIndex: Index { Index(.end) }
public var endIndex: Index {
Index(.end)
}
@inlinable
public subscript(position: Index) -> Result {
switch position.representation {
case .start: return initial
case .base(_, let result): return result
case .end: fatalError("Cannot get element of end index.")
case .base(_, let result):
return result
case .end:
fatalError("Cannot get element of end index.")
}
}
@inlinable
public func index(after i: Index) -> Index {
func index(base index: Base.Index, previous: Result) -> Index {
guard index != base.endIndex else { return endIndex }
var previous = previous
transform(&previous, base[index])
return Index(.base(index: index, result: previous))
}
switch i.representation {
case .start:
return index(base: base.startIndex, previous: initial)
case let .base(i, result):
return index(base: base.index(after: i), previous: result)
public func index(after index: Index) -> Index {
switch index.representation {
case .base(base.endIndex, _):
return Index(.end)
case .base(let index, var result):
transform(&result, base[index])
return Index(.base(base.index(after: index), result))
case .end:
fatalError("Cannot get index after end index.")
}
@@ -294,38 +319,40 @@ extension ExclusiveReductions: Collection where Base: Collection {
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
switch (start.representation, end.representation) {
case (.start, .start):
return 0
case let (.start, .base(index, _)):
return base.distance(from: base.startIndex, to: index) + 1
case (.start, .end):
return base.distance(from: base.startIndex, to: base.endIndex) + 1
case let (.base(index, _), .start):
return base.distance(from: index, to: base.startIndex) - 1
case let (.base(start, _), .base(end, _)):
return base.distance(from: start, to: end)
case let (.base(index, _), .end):
return base.distance(from: index, to: base.endIndex)
case (.end, .start):
return base.distance(from: base.endIndex, to: base.startIndex) - 1
return base.distance(from: index, to: base.endIndex) + 1
case let (.end, .base(index, _)):
return base.distance(from: base.endIndex, to: index)
return base.distance(from: base.endIndex, to: index) - 1
case (.end, .end):
return 0
}
}
}
extension ExclusiveReductions: LazySequenceProtocol
where Base: LazySequenceProtocol {}
extension ExclusiveReductionsSequence: LazySequenceProtocol {}
extension ExclusiveReductions: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
extension ExclusiveReductionsSequence: LazyCollectionProtocol
where Base: Collection {}
extension ExclusiveReductionsSequence.Index: Hashable
where Base.Index: Hashable
{
@inlinable
public func hash(into hasher: inout Hasher) {
switch representation {
case .base(let base, _):
hasher.combine(base)
case .end:
break
}
}
}
// MARK: - Inclusive Reductions
extension LazySequenceProtocol {
/// Returns a sequence containing the accumulated results of combining the
/// elements of the sequence using the given closure.
///
@@ -339,22 +366,20 @@ extension LazySequenceProtocol {
/// // prints [1, 3, 6, 10]
/// ```
///
/// - Parameters:
/// - transform: A closure that combines the previously reduced result and
/// the next element in the receiving sequence.
/// - Parameter transform: A closure that combines the previously reduced
/// result and the next element in the receiving sequence.
/// - Returns: A sequence of the reduced elements.
///
/// - Complexity: O(1)
@inlinable
public func reductions(
_ transform: @escaping (Element, Element) -> Element
) -> InclusiveReductions<Self> {
InclusiveReductions(base: self, transform: transform)
) -> InclusiveReductionsSequence<Elements> {
InclusiveReductionsSequence(base: elements, transform: transform)
}
}
extension Sequence {
/// Returns an array containing the accumulated results of combining the
/// elements of the sequence using the given closure.
///
@@ -384,9 +409,8 @@ extension Sequence {
/// If the sequence has one element, `transform` is never executed and
/// an array containing only that first element is returned.
///
/// - Parameters:
/// - transform: A closure that combines the previously reduced result and
/// the next element in the receiving sequence.
/// - Parameter transform: A closure that combines the previously reduced
/// result and the next element in the receiving sequence.
/// - Returns: An array of the reduced elements.
///
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
@@ -400,7 +424,7 @@ extension Sequence {
}
}
public struct InclusiveReductions<Base: Sequence> {
public struct InclusiveReductionsSequence<Base: Sequence> {
@usableFromInline
internal let base: Base
@@ -417,7 +441,7 @@ public struct InclusiveReductions<Base: Sequence> {
}
}
extension InclusiveReductions: Sequence {
extension InclusiveReductionsSequence: Sequence {
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var iterator: Base.Iterator
@@ -431,11 +455,9 @@ extension InclusiveReductions: Sequence {
@inlinable
internal init(
iterator: Base.Iterator,
element: Base.Element? = nil,
transform: @escaping (Base.Element, Base.Element) -> Base.Element
) {
self.iterator = iterator
self.element = element
self.transform = transform
}
@@ -453,139 +475,97 @@ extension InclusiveReductions: Sequence {
@inlinable
public func makeIterator() -> Iterator {
Iterator(iterator: base.makeIterator(),
transform: transform)
Iterator(iterator: base.makeIterator(), transform: transform)
}
}
extension InclusiveReductions: Collection where Base: Collection {
extension InclusiveReductionsSequence: Collection where Base: Collection {
public struct Index: Comparable {
@usableFromInline
internal let representation: ReductionsIndexRepresentation<Base.Index, Base.Element>
internal let base: Base.Index
@usableFromInline
internal let result: Element?
@inlinable
internal init(
_ representation: ReductionsIndexRepresentation<Base.Index, Base.Element>
) {
self.representation = representation
internal init(base: Base.Index, result: Element?) {
self.base = base
self.result = result
}
@inlinable
public static func < (lhs: Self, rhs: Self) -> Bool {
lhs.representation < rhs.representation
lhs.base < rhs.base
}
@inlinable
public static func == (lhs: Self, rhs: Self) -> Bool {
lhs.base == rhs.base
}
}
@inlinable
public var startIndex: Index {
guard base.startIndex != base.endIndex else { return endIndex }
return Index(.start)
Index(base: base.startIndex, result: base.first)
}
@inlinable
public var endIndex: Index { Index(.end) }
@inlinable
public subscript(position: Index) -> Base.Element {
switch position.representation {
case .start: return base[base.startIndex]
case .base(_, let result): return result
case .end: fatalError("Cannot get element of end index.")
}
public var endIndex: Index {
Index(base: base.endIndex, result: nil)
}
@inlinable
public func index(after i: Index) -> Index {
func index(after i: Base.Index, previous: Base.Element) -> Index {
let index = base.index(after: i)
guard index != base.endIndex else { return endIndex }
return Index(.base(index: index, result: transform(previous, base[index])))
public subscript(index: Index) -> Base.Element {
guard let result = index.result else {
fatalError("Can't subscript using endIndex")
}
switch i.representation {
case .start:
return index(after: base.startIndex, previous: base[base.startIndex])
case let .base(i, element):
return index(after: i, previous: element)
case .end:
fatalError("Cannot get index after end index.")
return result
}
@inlinable
public func index(after index: Index) -> Index {
guard let result = index.result else {
fatalError("Can't advance past endIndex")
}
let index = base.index(after: index.base)
let nextResult = index == base.endIndex
? nil
: transform(result, base[index])
return Index(base: index, result: nextResult)
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
switch (start.representation, end.representation) {
case (.start, .start):
return 0
case let (.start, .base(index, _)):
return base.distance(from: base.startIndex, to: index)
case (.start, .end):
return base.distance(from: base.startIndex, to: base.endIndex)
case let (.base(index, _), .start):
return base.distance(from: index, to: base.startIndex)
case let (.base(start, _), .base(end, _)):
return base.distance(from: start, to: end)
case let (.base(index, _), .end):
return base.distance(from: index, to: base.endIndex)
case (.end, .start):
return base.distance(from: base.endIndex, to: base.startIndex)
case let (.end, .base(index, _)):
return base.distance(from: base.endIndex, to: index)
case (.end, .end):
return 0
}
base.distance(from: start.base, to: end.base)
}
}
extension InclusiveReductions: LazySequenceProtocol
where Base: LazySequenceProtocol {}
extension InclusiveReductionsSequence: LazySequenceProtocol {}
extension InclusiveReductions: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
extension InclusiveReductionsSequence: LazyCollectionProtocol
where Base: Collection {}
// MARK: - ReductionsIndexRepresentation
@usableFromInline
enum ReductionsIndexRepresentation<BaseIndex: Comparable, Result> {
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<Result>(
_ initial: Result,
_ transform: @escaping (Result, Element) -> Result
) -> ExclusiveReductions<Result, Self> {
) -> ExclusiveReductionsSequence<Elements, Result> {
reductions(initial, transform)
}
@@ -594,13 +574,12 @@ extension LazySequenceProtocol {
public func scan<Result>(
into initial: Result,
_ transform: @escaping (inout Result, Element) -> Void
) -> ExclusiveReductions<Result, Self> {
) -> ExclusiveReductionsSequence<Elements, Result> {
reductions(into: initial, transform)
}
}
extension Sequence {
@available(*, deprecated, message: "Use reductions(_:_:) instead.")
@inlinable
public func scan<Result>(
@@ -621,18 +600,16 @@ extension Sequence {
}
extension LazySequenceProtocol {
@available(*, deprecated, message: "Use reductions(_:) instead.")
@inlinable
public func scan(
_ transform: @escaping (Element, Element) -> Element
) -> InclusiveReductions<Self> {
) -> InclusiveReductionsSequence<Elements> {
reductions(transform)
}
}
extension Sequence {
@available(*, deprecated, message: "Use reductions(_:) instead.")
@inlinable
public func scan(
+25 -46
View File
@@ -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..<m, m..<e)
if m1 == e {
// Left-hand case: we have moved element j into position. if
// we haven't already, we can capture the return value which
// is in s1.
// Left-hand case: we have moved element j into position. If we haven't
// already, we can capture the return value which is in s1.
//
// Note: the STL breaks the loop into two just to avoid this
// comparison once the return value is known. I'm not sure
// it's a worthwhile optimization, though.
// Note: the STL breaks the loop into two just to avoid this comparison
// once the return value is known. I'm not sure it's a worthwhile
// optimization, though.
if ret == e { ret = s1 }
// If both regions were the same size, we're done.
if s1 == m { break }
}
// Now we have a smaller problem that is also a rotation, so we
// can adjust our bounds and repeat.
// Now we have a smaller problem that is also a rotation, so we can adjust
// our bounds and repeat.
//
// h i j[d e f g|a b c] or d e f[a b c|g h i j]
// ^ ^ ^ ^ ^ ^
@@ -195,8 +193,8 @@ extension MutableCollection {
return ret
}
/// Rotates the elements of this collection so that the element
/// at the specified index becomes the start of the collection.
/// Rotates the elements of this collection so that the element at the
/// specified index becomes the start of the collection.
///
/// Rotating a collection is equivalent to breaking the collection into two
/// sections at the index `newStart`, and then swapping those two sections.
@@ -221,8 +219,8 @@ extension MutableCollection {
}
extension MutableCollection where Self: BidirectionalCollection {
/// 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.
@@ -255,13 +253,13 @@ extension MutableCollection where Self: BidirectionalCollection {
return newStart == p ? q : p
}
/// Rotates the elements of this collection so that the element
/// at the specified index becomes the start of the collection.
/// Rotates the elements of this collection so that the element at the
/// specified index becomes the start of the collection.
///
/// Rotating a collection is equivalent to breaking the collection into two
/// sections at the index `newStart`, and then swapping those two sections.
/// In this example, the `numbers` array is rotated so that the element at
/// index `3` (`40`) is first:
/// sections at the index `newStart`, and then swapping those two sections. In
/// this example, the `numbers` array is rotated so that the element at index
/// `3` (`40`) is first:
///
/// var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
/// let oldStart = numbers.rotate(toStartAt: 3)
@@ -279,22 +277,3 @@ extension MutableCollection where Self: BidirectionalCollection {
rotate(subrange: startIndex..<endIndex, toStartAt: newStart)
}
}
// Deprecations
extension MutableCollection {
@available(*, deprecated, renamed: "rotate(subrange:toStartAt:)")
@discardableResult
public mutating func rotate(
subrange: Range<Index>,
at newStart: Index) -> Index
{
rotate(subrange: subrange, toStartAt: newStart)
}
@available(*, deprecated, renamed: "rotate(toStartAt:)")
@discardableResult
public mutating func rotate(at newStart: Index) -> Index {
rotate(toStartAt: newStart)
}
}
@@ -10,8 +10,9 @@
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// LazySplitSequence
// SplitSequence
//===----------------------------------------------------------------------===//
/// A sequence that lazily splits a base sequence into subsequences separated by
/// elements that satisfy the given `whereSeparator` predicate.
///
@@ -21,7 +22,7 @@
/// x.split(separator:maxSplits:omittingEmptySubsequences)
///
/// where `x` conforms to `LazySequenceProtocol`.
public struct LazySplitSequence<Base: Sequence> {
public struct SplitSequence<Base: Sequence> {
@usableFromInline
internal let base: Base
@@ -48,7 +49,7 @@ public struct LazySplitSequence<Base: Sequence> {
}
}
extension LazySplitSequence {
extension SplitSequence: Sequence {
public struct Iterator {
public typealias Element = [Base.Element]
@@ -85,9 +86,19 @@ extension LazySplitSequence {
self.omittingEmptySubsequences = omittingEmptySubsequences
}
}
@inlinable
public func makeIterator() -> Iterator {
Iterator(
base: base.makeIterator(),
whereSeparator: self.isSeparator,
maxSplits: self.maxSplits,
omittingEmptySubsequences: self.omittingEmptySubsequences
)
}
}
extension LazySplitSequence.Iterator: IteratorProtocol {
extension SplitSequence.Iterator: IteratorProtocol {
@inlinable
public mutating func next() -> Element? {
var currentElement = base.next()
@@ -128,17 +139,7 @@ extension LazySplitSequence.Iterator: IteratorProtocol {
}
}
extension LazySplitSequence: LazySequenceProtocol {
@inlinable
public func makeIterator() -> Iterator {
return Iterator(
base: base.makeIterator(),
whereSeparator: self.isSeparator,
maxSplits: self.maxSplits,
omittingEmptySubsequences: self.omittingEmptySubsequences
)
}
}
extension SplitSequence: LazySequenceProtocol {}
extension LazySequenceProtocol {
/// Lazily returns the longest possible subsequences of the sequence, in
@@ -230,10 +231,10 @@ extension LazySequenceProtocol {
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true,
whereSeparator isSeparator: @escaping (Element) -> Bool
) -> LazySplitSequence<Elements> {
) -> SplitSequence<Elements> {
precondition(maxSplits >= 0, "Must take zero or more splits")
return LazySplitSequence(
return SplitSequence(
base: elements,
isSeparator: isSeparator,
maxSplits: maxSplits,
@@ -320,10 +321,10 @@ extension LazySequenceProtocol where Element: Equatable {
separator: Element,
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true
) -> LazySplitSequence<Elements> {
) -> SplitSequence<Elements> {
precondition(maxSplits >= 0, "Must take zero or more splits")
return LazySplitSequence(
return SplitSequence(
base: elements,
isSeparator: { $0 == separator },
maxSplits: maxSplits,
@@ -333,8 +334,9 @@ extension LazySequenceProtocol where Element: Equatable {
}
//===----------------------------------------------------------------------===//
// LazySplitCollection
// SplitCollection
//===----------------------------------------------------------------------===//
/// A collection that lazily splits a base collection into subsequences
/// separated by elements that satisfy the given `whereSeparator` predicate.
///
@@ -343,8 +345,8 @@ extension LazySequenceProtocol where Element: Equatable {
/// x.split(maxSplits:omittingEmptySubsequences:whereSeparator)
/// x.split(separator:maxSplits:omittingEmptySubsequences)
///
/// where `x` conforms to `LazyCollectionProtocol`.
public struct LazySplitCollection<Base: Collection> {
/// where `x` conforms to `LazySequenceProtocol` and `Collection`.
public struct SplitCollection<Base: Collection> {
@usableFromInline
internal let base: Base
@@ -398,7 +400,7 @@ public struct LazySplitCollection<Base: Collection> {
}
}
extension LazySplitCollection: LazyCollectionProtocol {
extension SplitCollection: Collection {
/// Position of a subsequence in a split collection.
public struct Index: Comparable {
/// The range corresponding to the subsequence at this position.
@@ -475,7 +477,7 @@ extension LazySplitCollection: LazyCollectionProtocol {
}
var updatedSplitCount = splitCount
if end < base.endIndex {
if end != base.endIndex {
// This subsequence ends on a separator (and perhaps includes other
// separators, if we're omitting empty subsequences), so we've performed
// another split.
@@ -547,13 +549,16 @@ extension LazySplitCollection: LazyCollectionProtocol {
}
}
extension LazySplitCollection.Index: Hashable {
extension SplitCollection.Index: Hashable {
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(sequenceLength)
}
}
extension LazyCollectionProtocol {
extension SplitCollection: LazyCollectionProtocol {}
extension LazySequenceProtocol where Self: Collection, Elements: Collection {
/// Lazily returns the longest possible subsequences of the collection, in
/// order, that don't contain elements satisfying the given predicate.
///
@@ -641,10 +646,10 @@ extension LazyCollectionProtocol {
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true,
whereSeparator isSeparator: @escaping (Element) -> Bool
) -> LazySplitCollection<Elements> {
) -> SplitCollection<Elements> {
precondition(maxSplits >= 0, "Must take zero or more splits")
return LazySplitCollection(
return SplitCollection(
base: elements,
isSeparator: isSeparator,
maxSplits: maxSplits,
@@ -653,8 +658,9 @@ extension LazyCollectionProtocol {
}
}
extension LazyCollectionProtocol
where Element: Equatable {
extension LazySequenceProtocol
where Self: Collection, Elements: Collection, Element: Equatable
{
/// Lazily returns the longest possible subsequences of the collection, in
/// order, around elements equal to the given element.
///
@@ -737,10 +743,10 @@ where Element: Equatable {
separator: Element,
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true
) -> LazySplitCollection<Elements> {
) -> SplitCollection<Elements> {
precondition(maxSplits >= 0, "Must take zero or more splits")
return LazySplitCollection(
return SplitCollection(
base: elements,
isSeparator: { $0 == separator },
maxSplits: maxSplits,
+46 -41
View File
@@ -14,47 +14,46 @@
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a sequence stepping through the elements every `step` starting
/// at the first value. Any remainders of the stride will be trimmed.
/// Returns a sequence stepping through the elements every `step` starting at
/// the first value. Any remainders of the stride will be trimmed.
///
/// (0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10]
/// (0...10).striding(by: 3) // == [0, 3, 6, 9]
///
/// - Complexity: O(1). Access to successive values is O(k) where
/// _k_ is the striding `step`.
/// - Complexity: O(1). Access to successive values is O(k) where _k_ is the
/// striding `step`.
///
/// - Parameter step: The amount to step with each iteration.
/// - Returns: Returns a sequence for stepping through the
/// elements by the specified amount.
/// - Returns: Returns a sequence for stepping through the elements by the
/// specified amount.
@inlinable
public func striding(by step: Int) -> StrideSequence<Self> {
StrideSequence(base: self, stride: step)
public func striding(by step: Int) -> StridingSequence<Self> {
StridingSequence(base: self, stride: step)
}
}
extension Collection {
/// Returns a sequence stepping through the elements every `step` starting
/// at the first value. Any remainders of the stride will be trimmed.
/// Returns a sequence stepping through the elements every `step` starting at
/// the first value. Any remainders of the stride will be trimmed.
///
/// (0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10]
/// (0...10).striding(by: 3) // == [0, 3, 6, 9]
///
/// - Complexity: O(1). Access to successive values is O(1) if the
/// collection conforms to `RandomAccessCollection`; otherwise,
/// O(_k_), where _k_ is the striding `step`.
/// - Complexity: O(1). Access to successive values is O(1) if the collection
/// conforms to `RandomAccessCollection`; otherwise, O(_k_), where _k_ is
/// the striding `step`.
///
/// - Parameter step: The amount to step with each iteration.
/// - Returns: Returns a collection for stepping through the
/// elements by the specified amount.
/// - Returns: Returns a collection for stepping through the elements by the
/// specified amount.
@inlinable
public func striding(by step: Int) -> StrideCollection<Self> {
StrideCollection(base: self, stride: step)
public func striding(by step: Int) -> StridingCollection<Self> {
StridingCollection(base: self, stride: step)
}
}
/// A wrapper that strides over a base sequence.
public struct StrideSequence<Base: Sequence>: Sequence {
public struct StridingSequence<Base: Sequence> {
@usableFromInline
internal let base: Base
@@ -63,15 +62,21 @@ public struct StrideSequence<Base: Sequence>: Sequence {
@inlinable
internal init(base: Base, stride: Int) {
precondition(stride > 0, "striding must be greater than zero")
precondition(stride > 0, "Stride must be greater than zero")
self.base = base
self.stride = stride
}
}
extension StrideSequence {
/// An iterator over a `Stride` sequence.
extension StridingSequence {
@inlinable
public func striding(by step: Int) -> Self {
Self(base: base, stride: stride * step)
}
}
extension StridingSequence: Sequence {
/// An iterator over a `StridingSequence` instance.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var iterator: Base.Iterator
@@ -107,15 +112,11 @@ extension StrideSequence {
}
}
extension StrideSequence {
@inlinable
public func striding(by step: Int) -> Self {
Self(base: base, stride: stride * step)
}
}
extension StridingSequence: LazySequenceProtocol
where Base: LazySequenceProtocol {}
/// A wrapper that strides over a base collection.
public struct StrideCollection<Base: Collection> {
public struct StridingCollection<Base: Collection> {
@usableFromInline
internal let base: Base
@@ -130,16 +131,15 @@ public struct StrideCollection<Base: Collection> {
}
}
extension StrideCollection {
extension StridingCollection {
@inlinable
public func striding(by step: Int) -> Self {
Self(base: base, stride: stride * step)
}
}
extension StrideCollection: Collection {
/// A position in a `Stride` collection.
extension StridingCollection: Collection {
/// A position in a `StridingCollection` instance.
public struct Index: Comparable {
@usableFromInline
internal let base: Base.Index
@@ -172,7 +172,7 @@ extension StrideCollection: Collection {
@inlinable
public func index(after i: Index) -> Index {
precondition(i.base < base.endIndex, "Advancing past end index")
precondition(i.base != base.endIndex, "Advancing past end index")
return index(i, offsetBy: 1)
}
@@ -255,8 +255,8 @@ extension StrideCollection: Collection {
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
precondition(distance <= 0 || i.base < base.endIndex, "Advancing past end index")
precondition(distance >= 0 || i.base > base.startIndex, "Incrementing past start index")
precondition(distance <= 0 || i.base != base.endIndex, "Advancing past end index")
precondition(distance >= 0 || i.base != base.startIndex, "Incrementing past start index")
let limit = distance > 0 ? endIndex : startIndex
let idx = index(i, offsetBy: distance, limitedBy: limit)
precondition(idx != nil, "The distance \(distance) is not valid for this collection")
@@ -264,15 +264,20 @@ extension StrideCollection: Collection {
}
}
extension StrideCollection: BidirectionalCollection
extension StridingCollection: BidirectionalCollection
where Base: RandomAccessCollection {
@inlinable
public func index(before i: Index) -> Index {
precondition(i.base > base.startIndex, "Incrementing past start index")
precondition(i.base != base.startIndex, "Incrementing past start index")
return index(i, offsetBy: -1)
}
}
extension StrideCollection: RandomAccessCollection where Base: RandomAccessCollection {}
extension StrideCollection.Index: Hashable where Base.Index: Hashable {}
extension StridingCollection: RandomAccessCollection
where Base: RandomAccessCollection {}
extension StridingCollection: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazySequenceProtocol {}
extension StridingCollection.Index: Hashable where Base.Index: Hashable {}
+4 -4
View File
@@ -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
+51 -59
View File
@@ -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..<endIndex]
return self[start...]
}
}
@@ -42,19 +41,18 @@ extension Collection {
//===----------------------------------------------------------------------===//
extension Collection where Self: RangeReplaceableCollection {
/// Mutates a `Collection` by discarding all elements at the start
/// of it which satisfy the given predicate.
/// Mutates a `Collection` by discarding all elements at the start of it which
/// satisfy the given predicate.
///
/// This example uses `trimPrefix(while:)` to remove the white
/// space at the beginning of the string:
/// This example uses `trimPrefix(while:)` to remove the white space at the
/// beginning of the string:
///
/// let myString = " hello, world "
/// myString.trimPrefix(while: \.isWhitespace)
/// print(myString) // "hello, world "
///
/// - Parameters:
/// - predicate: A closure which determines if the element should be
/// removed from the string.
/// - Parameter predicate: A closure which determines if the element should be
/// removed from the string.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
///
@@ -69,19 +67,18 @@ extension Collection where Self: RangeReplaceableCollection {
}
extension Collection where Self == Self.SubSequence {
/// Mutates a `Collection` by discarding all elements at the start
/// of it which satisfy the given predicate.
/// Mutates a `Collection` by discarding all elements at the start of it which
/// satisfy the given predicate.
///
/// This example uses `trimPrefix(while:)` to remove the white
/// space at the beginning of the string:
/// This example uses `trimPrefix(while:)` to remove the white space at the
/// beginning of the string:
///
/// let myString = " hello, world "
/// myString.trimPrefix(while: \.isWhitespace)
/// print(myString) // "hello, world "
///
/// - Parameters:
/// - predicate: A closure which determines if the element should be
/// removed from the string.
/// - Parameters predicate: A closure which determines if the element should
/// be removed from the string.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
///
@@ -107,9 +104,8 @@ extension BidirectionalCollection {
/// let myString = " hello, world "
/// print(myString.trimming(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.
///
@@ -117,21 +113,20 @@ extension BidirectionalCollection {
public func trimming(
while predicate: (Element) throws -> 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..<end]
return self[..<end]
}
}
@@ -149,19 +144,18 @@ extension BidirectionalCollection {
//===----------------------------------------------------------------------===//
extension BidirectionalCollection where Self: RangeReplaceableCollection {
/// Mutates a `BidirectionalCollection` by discarding all elements at the start
/// and at the end of it which satisfy the given predicate.
/// Mutates a `BidirectionalCollection` by discarding all elements at the
/// start and at the end of it which satisfy the given predicate.
///
/// This example uses `trim(while:)` to remove the white
/// space at the beginning of the string:
/// This example uses `trim(while:)` to remove the white space at the
/// beginning of the string:
///
/// let myString = " hello, world "
/// myString.trim(while: \.isWhitespace)
/// print(myString) // "hello, world"
///
/// - Parameters:
/// - predicate: A closure which determines if the element should be
/// removed from the string.
/// - Parameter predicate: A closure which determines if the element should be
/// removed from the string.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
///
@@ -170,22 +164,22 @@ extension BidirectionalCollection where Self: RangeReplaceableCollection {
public mutating func trim(
while predicate: (Element) throws -> Bool
) rethrows {
replaceSubrange(startIndex..<endIndex, with: try trimming(while: predicate))
try trimSuffix(while: predicate)
try trimPrefix(while: predicate)
}
/// Mutates a `BidirectionalCollection` by discarding all elements at the end
/// of it which satisfy the given predicate.
///
/// This example uses `trimSuffix(while:)` to remove the white
/// space at the beginning of the string:
/// This example uses `trimSuffix(while:)` to remove the white space at the
/// beginning of the string:
///
/// let myString = " hello, world "
/// myString.trimSuffix(while: \.isWhitespace)
/// print(myString) // " hello, world"
///
/// - Parameters:
/// - predicate: A closure which determines if the element should be
/// removed from the string.
/// - Parameter predicate: A closure which determines if the element should be
/// removed from the string.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
///
@@ -200,19 +194,18 @@ extension BidirectionalCollection where Self: RangeReplaceableCollection {
}
extension BidirectionalCollection where Self == Self.SubSequence {
/// Mutates a `BidirectionalCollection` by discarding all elements at the start
/// and at the end of it which satisfy the given predicate.
/// Mutates a `BidirectionalCollection` by discarding all elements at the
/// start and at the end of it which satisfy the given predicate.
///
/// This example uses `trim(while:)` to remove the white
/// space at the beginning of the string:
/// This example uses `trim(while:)` to remove the white space at the
/// beginning of the string:
///
/// let myString = " hello, world "
/// myString.trim(while: \.isWhitespace)
/// print(myString) // "hello, world"
///
/// - Parameters:
/// - predicate: A closure which determines if the element should be
/// removed from the string.
/// - Parameter predicate: A closure which determines if the element should be
/// removed from the string.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
///
@@ -226,16 +219,15 @@ extension BidirectionalCollection where Self == Self.SubSequence {
/// Mutates a `BidirectionalCollection` by discarding all elements at the end
/// of it which satisfy the given predicate.
///
/// This example uses `trimSuffix(while:)` to remove the white
/// space at the beginning of the string:
/// This example uses `trimSuffix(while:)` to remove the white space at the
/// beginning of the string:
///
/// let myString = " hello, world "
/// myString.trimSuffix(while: \.isWhitespace)
/// print(myString) // " hello, world"
///
/// - Parameters:
/// - predicate: A closure which determines if the element should be
/// removed from the string.
/// - Parameter predicate: A closure which determines if the element should be
/// removed from the string.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
///
+12 -11
View File
@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
/// A sequence wrapper that leaves out duplicate elements of a base sequence.
public struct Uniqued<Base: Sequence, Subject: Hashable> {
public struct UniquedSequence<Base: Sequence, Subject: Hashable> {
/// The base collection.
@usableFromInline
internal let base: Base
@@ -26,8 +26,8 @@ public struct Uniqued<Base: Sequence, Subject: Hashable> {
}
}
extension Uniqued: Sequence {
/// The iterator for a `Uniqued` sequence.
extension UniquedSequence: Sequence {
/// The iterator for a `UniquedSequence` instance.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var base: Base.Iterator
@@ -64,7 +64,8 @@ extension Uniqued: Sequence {
}
}
extension Uniqued: LazySequenceProtocol where Base: LazySequenceProtocol {}
extension UniquedSequence: LazySequenceProtocol
where Base: LazySequenceProtocol {}
//===----------------------------------------------------------------------===//
// uniqued()
@@ -83,8 +84,8 @@ extension Sequence where Element: Hashable {
/// .
/// - Complexity: O(1).
@inlinable
public func uniqued() -> Uniqued<Self, Element> {
Uniqued(base: self, projection: { $0 })
public func uniqued() -> UniquedSequence<Self, Element> {
UniquedSequence(base: self, projection: { $0 })
}
}
@@ -102,9 +103,9 @@ extension Sequence {
/// // Prints '["dog", "pig", "cat", "ox"]'
///
/// - Parameter projection: A closure that transforms an element into the
/// value to use for uniqueness. If `projection` returns the same value
/// for two different elements, the second element will be excluded
/// from the resulting array.
/// value to use for uniqueness. If `projection` returns the same value for
/// two different elements, the second element will be excluded from the
/// resulting array.
///
/// - Returns: An array with only the unique elements of this sequence, as
/// determined by the result of `projection` for each element.
@@ -138,7 +139,7 @@ extension LazySequenceProtocol {
@inlinable
public func uniqued<Subject: Hashable>(
on projection: @escaping (Element) -> Subject
) -> Uniqued<Self, Subject> {
Uniqued(base: self, projection: projection)
) -> UniquedSequence<Self, Subject> {
UniquedSequence(base: self, projection: projection)
}
}
+41 -34
View File
@@ -39,35 +39,35 @@ extension Collection {
/// `RandomAccessCollection`, otherwise O(*k*) where `k` is `count`.
/// Access to successive windows is O(1).
@inlinable
public func windows(ofCount count: Int) -> Windows<Self> {
Windows(base: self, size: count)
public func windows(ofCount count: Int) -> WindowsOfCountCollection<Self> {
WindowsOfCountCollection(base: self, windowSize: count)
}
}
/// A collection wrapper that presents a sliding window over the elements of
/// a collection.
public struct Windows<Base: Collection> {
public struct WindowsOfCountCollection<Base: Collection> {
@usableFromInline
internal let base: Base
@usableFromInline
internal let size: Int
internal let windowSize: Int
@usableFromInline
internal var firstUpperBound: Base.Index?
internal var endOfFirstWindow: Base.Index?
@inlinable
internal init(base: Base, size: Int) {
precondition(size > 0, "Windows size must be greater than zero")
internal init(base: Base, windowSize: Int) {
precondition(windowSize > 0, "Windows size must be greater than zero")
self.base = base
self.size = size
self.firstUpperBound =
base.index(base.startIndex, offsetBy: size, limitedBy: base.endIndex)
self.windowSize = windowSize
self.endOfFirstWindow =
base.index(base.startIndex, offsetBy: windowSize, limitedBy: base.endIndex)
}
}
extension Windows: Collection {
/// A position in a `Windows` collection.
extension WindowsOfCountCollection: Collection {
/// A position in a `WindowsOfCountCollection` instance.
public struct Index: Comparable {
@usableFromInline
internal var lowerBound: Base.Index
@@ -94,7 +94,7 @@ extension Windows: Collection {
@inlinable
public var startIndex: Index {
if let upperBound = firstUpperBound {
if let upperBound = endOfFirstWindow {
return Index(lowerBound: base.startIndex, upperBound: upperBound)
} else {
return endIndex
@@ -116,12 +116,14 @@ extension Windows: Collection {
@inlinable
public func index(after index: Index) -> Index {
precondition(index < endIndex, "Advancing past end index")
precondition(index != endIndex, "Advancing past end index")
guard index.upperBound < base.endIndex else { return endIndex }
return Index(
lowerBound: base.index(after: index.lowerBound),
upperBound: base.index(after: index.upperBound)
)
let lowerBound = windowSize == 1
? index.upperBound
: base.index(after: index.lowerBound)
let upperBound = base.index(after: index.upperBound)
return Index(lowerBound: lowerBound, upperBound: upperBound)
}
@inlinable
@@ -185,7 +187,7 @@ extension Windows: Collection {
// |> > >|>| or |> > >|
// output: [x x x x x|x x x x x] [x x x x x x x x x x] (`endIndex`)
if distance >= size {
if distance >= windowSize {
// Avoid traversing `self[i.lowerBound..<i.upperBound]` when the lower
// bound of the output is greater than or equal to the upper bound of the
// input.
@@ -197,11 +199,11 @@ extension Windows: Collection {
guard limit.lowerBound >= i.upperBound,
let lowerBound = base.index(
i.upperBound,
offsetBy: distance - size,
offsetBy: distance - windowSize,
limitedBy: limit.lowerBound),
let indexBeforeUpperBound = base.index(
lowerBound,
offsetBy: size - 1,
offsetBy: windowSize - 1,
limitedBy: limit.upperBound)
else { return nil }
@@ -262,9 +264,9 @@ extension Windows: Collection {
else { return nil }
return Index(
lowerBound: base.index(upperBound, offsetBy: -size),
lowerBound: base.index(upperBound, offsetBy: -windowSize),
upperBound: upperBound)
} else if distance >= size {
} else if distance >= windowSize {
// Avoid traversing `self[i.lowerBound..<i.upperBound]` when the upper
// bound of the output is less than or equal to the lower bound of the
// input.
@@ -276,12 +278,12 @@ extension Windows: Collection {
guard limit.upperBound <= i.lowerBound,
let upperBound = base.index(
i.lowerBound,
offsetBy: -(distance - size),
offsetBy: -(distance - windowSize),
limitedBy: limit.upperBound)
else { return nil }
return Index(
lowerBound: base.index(upperBound, offsetBy: -size),
lowerBound: base.index(upperBound, offsetBy: -windowSize),
upperBound: upperBound)
} else {
// input: [x x x x x|x x x x x x|x]
@@ -304,7 +306,7 @@ extension Windows: Collection {
public func distance(from start: Index, to end: Index) -> Int {
guard start <= end else { return -distance(from: end, to: start) }
guard start != end else { return 0 }
guard end < endIndex else {
guard end != endIndex else {
// We add 1 here because the index before `endIndex` also has
// `base.endIndex` as its upper bound.
return base[start.upperBound...].count + 1
@@ -318,7 +320,7 @@ extension Windows: Collection {
// |- - - -|> >|
// end: [x x x x x x x|x x x x|x]
return size + base[start.upperBound..<end.lowerBound].count
return windowSize + base[start.upperBound..<end.lowerBound].count
} else {
// start: [x|x x x x x x|x x x x x]
// |> > > >|
@@ -329,13 +331,15 @@ extension Windows: Collection {
}
}
extension Windows: BidirectionalCollection where Base: BidirectionalCollection {
extension WindowsOfCountCollection: BidirectionalCollection
where Base: BidirectionalCollection
{
@inlinable
public func index(before index: Index) -> Index {
precondition(index > startIndex, "Incrementing past start index")
precondition(index != startIndex, "Incrementing past start index")
if index == endIndex {
return Index(
lowerBound: base.index(index.lowerBound, offsetBy: -size),
lowerBound: base.index(index.lowerBound, offsetBy: -windowSize),
upperBound: index.upperBound
)
} else {
@@ -347,7 +351,10 @@ extension Windows: BidirectionalCollection where Base: BidirectionalCollection {
}
}
extension Windows: LazySequenceProtocol where Base: LazySequenceProtocol {}
extension Windows: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
extension Windows: RandomAccessCollection where Base: RandomAccessCollection {}
extension Windows.Index: Hashable where Base.Index: Hashable {}
extension WindowsOfCountCollection: RandomAccessCollection
where Base: RandomAccessCollection {}
extension WindowsOfCountCollection: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazySequenceProtocol {}
extension WindowsOfCountCollection.Index: Hashable where Base.Index: Hashable {}