Compare commits

..
25 changed files with 213 additions and 835 deletions

No files matched your search

+2 -72
View File
@@ -8,7 +8,7 @@ This project follows semantic versioning. While still in major version `0`,
source-stability is only guaranteed within minor versions (e.g. between
`0.0.3` and `0.0.4`). If you want to guard against potentially source-breaking
package updates, you can specify your package dependency using
`.upToNextMinor(from: "0.1.0")` as the requirement.
`.upToNextMinor(from: "0.0.1")` as the requirement.
## [Unreleased]
@@ -16,59 +16,6 @@ package updates, you can specify your package dependency using
---
## [0.1.0] - 2021-04-13
### Additions
- The `compacted()` method lazily finds the non-`nil` elements of a sequence or
collection ([#112]).
### Changes
- The `uniqued()` method now lazily computes the unique elements of a sequence
or a collection ([#71]). Pass this resulting sequence to an `Array`
initializer to recover the behavior of the previous release.
- Calling `cycled(times:)` now returns a new `FiniteCycle` type, which has the
same conformances as its underlying collection ([#106]).
- The base collections of the sequence and collection wrapper types are no
longer public ([#85], [#125]), and the wrapper types no longer conform to the
`Equatable` or `Hashable` protocols ([#124]). If you need those conformances,
convert the wrapper type to an `Array` or other collection currrency type
before storing. Please file an issue if these changes pose a problem for your
use case.
The 0.1.0 release includes contributions from [LemonSpike], [LucianoPAlmeida],
[natecook1000], and [timvermeulen]. Thank you!
---
## [0.0.4] - 2021-03-29
### Additions
More new algorithms to join the party:
- A lazy version of the standard library's two `split` methods. ([#78])
- `firstNonNil(_:)` returns the first non-`nil` element from an
optional-generating transform. ([#31])
- `uniquePermutations()` skips duplicates when generating permutations of a
collection. ([#91])
- The `reductions` methods return all the in-between states of reducing a
sequence or collection. ([#46])
### Fixes
- Methods and computed properties are more consistently marked as inlinable,
resolving a performance regression.
- The `Stride` type now efficiently calculates distances between positions,
supported by the underlying collection.
- Better test coverage and improved diagnostics for comparing sequences.
- Fixed links and improved documentation.
The 0.0.4 release includes contributions from [bjhomer], [danielctull],
[hashemi], [karwa], [kylemacomber], [LucianoPAlmeida], [mdznr], [natecook1000],
[ollieatkinson], [Qata], [timvermeulen], and [toddthomas]. Thank you!
## [0.0.3] - 2021-02-26
### Additions
@@ -149,9 +96,7 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
<!-- Link references for releases -->
[Unreleased]: https://github.com/apple/swift-algorithms/compare/0.1.0...HEAD
[0.1.0]: https://github.com/apple/swift-algorithms/compare/0.0.4...0.1.0
[0.0.4]: https://github.com/apple/swift-algorithms/compare/0.0.3...0.0.4
[Unreleased]: https://github.com/apple/swift-algorithms/compare/0.0.3...HEAD
[0.0.3]: https://github.com/apple/swift-algorithms/compare/0.0.2...0.0.3
[0.0.2]: https://github.com/apple/swift-algorithms/compare/0.0.1...0.0.2
[0.0.1]: https://github.com/apple/swift-algorithms/releases/tag/0.0.1
@@ -162,37 +107,24 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
[#9]: https://github.com/apple/swift-algorithms/pull/9
[#20]: https://github.com/apple/swift-algorithms/pull/20
[#24]: https://github.com/apple/swift-algorithms/pull/24
[#31]: https://github.com/apple/swift-algorithms/pull/31
[#35]: https://github.com/apple/swift-algorithms/pull/35
[#46]: https://github.com/apple/swift-algorithms/pull/46
[#51]: https://github.com/apple/swift-algorithms/pull/51
[#54]: https://github.com/apple/swift-algorithms/pull/54
[#56]: https://github.com/apple/swift-algorithms/pull/56
[#65]: https://github.com/apple/swift-algorithms/pull/65
[#71]: https://github.com/apple/swift-algorithms/pull/71
[#77]: https://github.com/apple/swift-algorithms/pull/77
[#78]: https://github.com/apple/swift-algorithms/pull/78
[#85]: https://github.com/apple/swift-algorithms/pull/85
[#91]: https://github.com/apple/swift-algorithms/pull/91
[#106]: https://github.com/apple/swift-algorithms/pull/106
[#112]: https://github.com/apple/swift-algorithms/pull/112
[#124]: https://github.com/apple/swift-algorithms/pull/124
[#125]: https://github.com/apple/swift-algorithms/pull/125
<!-- Link references for contributors -->
[AustinConlon]: https://github.com/apple/swift-algorithms/commits?author=AustinConlon
[benrimmington]: https://github.com/apple/swift-algorithms/commits?author=benrimmington
[bjhomer]: https://github.com/apple/swift-algorithms/commits?author=bjhomer
[danielctull]: https://github.com/apple/swift-algorithms/commits?author=danielctull
[dhruvshah8]: https://github.com/apple/swift-algorithms/commits?author=dhruvshah8
[egorzhdan]: https://github.com/apple/swift-algorithms/commits?author=egorzhdan
[hashemi]: https://github.com/apple/swift-algorithms/commits?author=hashemi
[IanKeen]: https://github.com/apple/swift-algorithms/commits?author=IanKeen
[iSame7]: https://github.com/apple/swift-algorithms/commits?author=iSame7
[karwa]: https://github.com/apple/swift-algorithms/commits?author=karwa
[kylemacomber]: https://github.com/apple/swift-algorithms/commits?author=kylemacomber
[LemonSpike]: https://github.com/apple/swift-algorithms/commits?author=LemonSpike
[LucianoPAlmeida]: https://github.com/apple/swift-algorithms/commits?author=LucianoPAlmeida
[markuswntr]: https://github.com/apple/swift-algorithms/commits?author=markuswntr
[mdznr]: https://github.com/apple/swift-algorithms/commits?author=mdznr
@@ -201,7 +133,6 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
[nordicio]: https://github.com/apple/swift-algorithms/commits?author=nordicio
[ollieatkinson]: https://github.com/apple/swift-algorithms/commits?author=ollieatkinson
[pmtao]: https://github.com/apple/swift-algorithms/commits?author=pmtao
[Qata]: https://github.com/apple/swift-algorithms/commits?author=Qata
[rakaramos]: https://github.com/apple/swift-algorithms/commits?author=rakaramos
[rockbruno]: https://github.com/apple/swift-algorithms/commits?author=rockbruno
[Roshankumar350]: https://github.com/apple/swift-algorithms/commits?author=Roshankumar350
@@ -209,4 +140,3 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
[sidepelican]: https://github.com/apple/swift-algorithms/commits?author=sidepelican
[stephentyrone]: https://github.com/apple/swift-algorithms/commits?author=stephentyrone
[timvermeulen]: https://github.com/apple/swift-algorithms/commits?author=timvermeulen
[toddthomas]: https://github.com/apple/swift-algorithms/commits?author=toddthomas
+3 -3
View File
@@ -76,15 +76,15 @@ extension Collection {
extension LazyCollectionProtocol {
public func chunked(
by belongInSameGroup: @escaping (Element, Element) -> Bool
) -> Chunked<Elements>
) -> LazyChunked<Elements>
public func chunked<Subject: Equatable>(
on projection: @escaping (Element) -> Subject
) -> Chunked<Elements>
) -> LazyChunked<Elements>
}
```
The `Chunked` type is bidirectional when the wrapped collection is
The `LazyChunked` type is bidirectional when the wrapped collection is
bidirectional.
### Complexity
-47
View File
@@ -1,47 +0,0 @@
# Compacted
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Compacted.swift) |
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/CompactedTests.swift)]
A convenience method that lazily flattens the `nil`s out of a sequence
or collection.
The new method matches one of the most common uses of `compactMap`,
which is to only remove `nil`s without transforming the elements
(e.g. `collection.lazy.compactMap { $0 }`).
```swift
let array: [Int?] = [10, nil, 30, nil, 2, 3, nil, 5]
let withNoNils = array.compacted()
// Array(withNoNils) == [10, 30, 2, 3, 5]
```
The type returned by `compacted()` lazily computes the non-`nil` elements
without requiring a user to provide a closure or use the `.lazy` property.
## Detailed Design
The `compacted()` methods has two overloads:
```swift
extension Sequence {
public func compacted<Unwrapped>() -> CompactedSequence<Self, Unwrapped>
where Element == Unwrapped?
}
extension Collection {
public func compacted<Unwrapped>() -> CompactedCollection<Self, Unwrapped>
where Element == Unwrapped?
}
```
The `Sequence` version of `compacted()` returns a `CompactedSequence` type,
while the `Collection` version returns `CompactedCollection`. The collection
has conditional conformance to `BidirectionalCollection` and
`LazyCollectionProtocol` when the base collection conforms.
### Naming
The name `compacted()` matches the existing method `compactMap`,
which is commonly used to extract only the non-`nil` values
without mapping them to a different type.
+8 -9
View File
@@ -16,9 +16,9 @@ for x in (1...3).cycled(times: 3) {
// Prints 1 through 3 three times
```
`cycled(times:)` provides a more expressive way of repeating a
collection's elements a limited number of times than
combining `repeatElement(_:count:)` and `joined()`.
`cycled(times:)` combines two other existing standard library functions
(`repeatElement` and `joined`) to provide a more expressive way of repeating a
collection's elements a limited number of times.
## Detailed Design
@@ -28,7 +28,7 @@ Two new methods are added to collections:
extension Collection {
func cycled() -> Cycle<Self>
func cycled(times: Int) -> FiniteCycle<Self>
func cycled(times: Int) -> FlattenSequence<Repeated<Self>>
}
```
@@ -36,10 +36,9 @@ The new `Cycle` type is a sequence only, given that the `Collection` protocol
design makes infinitely large types impossible/impractical. `Cycle` also
conforms to `LazySequenceProtocol` when the base type conforms.
The `FiniteCycle` type always has `Collection` conformance, with
`BidirectionalCollection` conformance
when called on a bidirectional collection. `FiniteCycle` also
conforms to `LazyCollectionProtocol` when the base type conforms.
Note that despite its name, the returned `FlattenSequence` will always have
`Collection` conformance, and will have `BidirectionalCollection` conformance
when called on a bidirectional collection.
### Complexity
@@ -62,4 +61,4 @@ anything that matches the `cycled(times:)` behavior.
`cycled(times:)` here.
**Python:** Python’s `itertools` includes a `cycle` method, which caches the
elements of the iterator on the first pass.
elements of the iterator on the first pass.
+18 -60
View File
@@ -2,48 +2,23 @@
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/FirstNonNil.swift) |
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/FirstNonNilTests.swift)]
Returns the first non-`nil` result obtained from applying the given
transformation to the elements of the sequence.
Retrieves the first `.some` encountered while applying the given transform.
This operation is available through the `firstNonNil(_:)` method on any sequence.
```swift
let strings = ["three", "3.14", "-5", "2"]
if let firstInt = strings.firstNonNil({ Int($0) }) {
print(firstInt)
// -5
}
let value = ["A", "B", "10"].firstNonNil { Int($0) }
// value == .some(10)
//
let noValue = ["A", "B", "C"].firstNonNil { Int($0) }
// noValue == .none
```
Like `first(where:)`, this method stops iterating the sequence once a match is
found. Use `firstNonNil(_:)` to avoid having to apply a transformation twice:
```swift
let strings = ["three", "3.14", "-5", "2"]
if let firstIntAsString = strings.first(where: { Int($0) != nil }) {
let firstInt = Int(firstIntAsString)! // :(
// ...
}
```
This method's behavior can also be approximated using `compactMap(_:)`:
```swift
let strings = ["three", "3.14", "-5", "2"]
if let firstInt = strings.compactMap({ Int($0) }).first {
// ...
}
```
However, unlike `firstNonNil(_:)` and `first(where:)`, `compactMap(_:)` does not
stop iterating the sequence once the first match is found. Adding `.lazy` fixes
this, at the cost of requiring an escaping closure that you cannot `throw` from:
```swift
let strings = ["three", "3.14", "-5", "2"]
if let firstInt = strings.lazy.compactMap({ Int($0) }).first {
// ...
}
```
This method is analogous to `first(where:)` in how it only consumes values until
a `.some` is found, unlike using lazy operators, which will load any sequence into a collection
before evaluating its transforms lazily.
## Detailed Design
@@ -52,34 +27,17 @@ protocol:
```swift
public extension Sequence {
func firstNonNil<Result>(
_ transform: (Element) throws -> Result?
) rethrows -> Result?
func firstNonNil<Result>(_ transform: (Element) throws -> Result?)
rethrows -> Result?
}
```
### Complexity
`firstNonNil(_:)` is an O(*n*) operation, where *n* is the number of
elements at the start of the sequence that result in `nil` when applying the
transformation.
### Naming
Some alternative names were considered:
* `compactMapFirst(_:)`
* `first(mapping:)`
* `firstSome(_:)`
* `firstMap(_:)`
This method’s name was selected for its comprehensibility.
### Comparison with other languages
**Haskell**: Haskell includes the `firstJust` method, which has the same
semantics as the `firstNonNil(_:)` method.
**Rust**: Rust includes the `find_map` method, which has the same semantics as
the `firstNonNil(_:)` method.
**Scala**: Scala includes the `collectFirst` method, which has the same
semantics as the `firstNonNil(_:)` method.
**Scala**: Scala provides a `collectFirst` function that finds the first element
in a collection for which a partial function is defined.
+5 -3
View File
@@ -3,7 +3,9 @@
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Reductions.swift) |
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/ReductionsTests.swift)]
Produces all the intermediate results of reducing a sequence's elements using a closure.
Produces a sequence of values.
This has the behaviour of reduce, but also returns all intermediate results.
```swift
let exclusiveRunningTotal = (1...5).reductions(0, +)
@@ -110,7 +112,7 @@ these terms carry through as the name for the lazy sequences;
[David Rönnqvist]: https://forums.swift.org/t/review-se-0045-add-scan-prefix-while-drop-while-and-iterate-to-the-stdlib/2382/8
[Kyle Macomber]: https://github.com/apple/swift-algorithms/issues/25#issuecomment-709317894
### Comparison with other languages
### Comparison with other langauges
**C++:** As of C++17, the `<algorithm>` library includes both
[`exclusive_scan`][C++ Exclusive] and [`inclusive_scan`][C++ Inclusive]
@@ -122,7 +124,7 @@ functions.
`Traversable` type, which is akin to Swift's `Sequence`.
**Python:** Python’s `itertools` includes an `accumulate` method. In version
3.3, a function parameter was added. Version 3.8 added the optional initial
3.3, a function paramenter was added. Version 3.8 added the optional initial
parameter.
**[Rust][Rust]:** Rust provides a `scan` function.
+1 -1
View File
@@ -101,7 +101,7 @@ let result = myString.drop(while: \.isWhitespace)
```
With a lazy filter that drops _all_ whitespace characters regardless of where they are in the string.
Besides that, the root `trim` leads to clearer, more concise code, which is more aligned with other programming
Besides that, the root `trim` leads to clearer, more conscise code, which is more aligned with other programming
languages:
```swift
+7 -14
View File
@@ -5,7 +5,7 @@
Methods to strip repeated elements from a sequence or collection.
The `uniqued()` method returns a sequence, dropping duplicate elements
The `uniqued()` method returns an array, dropping duplicate elements
from a sequence. The `uniqued(on:)` method does the same, using
the result of the given closure to determine the "uniqueness" of each
element.
@@ -14,36 +14,29 @@ element.
let numbers = [1, 2, 3, 3, 2, 3, 3, 2, 2, 2, 1]
let unique = numbers.uniqued()
// Array(unique) == [1, 2, 3]
// unique == [1, 2, 3]
```
## Detailed Design
Both methods are available for sequences, with the simplest limited to
when the element type conforms to `Hashable`. Both methods preserve
the relative order of the elements. `uniqued(on:)` has a matching lazy
version that is added to `LazySequenceProtocol`.
the relative order of the elements.
```swift
extension Sequence where Element: Hashable {
func uniqued() -> Uniqued<Self, Element>
func uniqued() -> [Element]
}
extension Sequence {
func uniqued<Subject>(on projection: (Element) throws -> Subject) rethrows -> [Element]
where Subject: Hashable
}
extension LazySequenceProtocol {
func uniqued<Subject>(on projection: @escaping (Element) -> Subject) -> Uniqued<Self, Subject>
where Subject: Hashable
func uniqued<T>(on: (Element) throws -> T) rethrows -> [Element]
where T: Hashable
}
```
### Complexity
The eager `uniqued(on:)` method is O(_n_) in both time and space complexity.
The lazy versions are O(_1_).
The `uniqued` methods are O(_n_) in both time and space complexity.
### Comparison with other languages
+5 -8
View File
@@ -25,12 +25,9 @@ Read more about the package, and the intent behind it, in the [announcement on s
#### Subsetting operations
- [`compacted()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Compacted.md): Drops the `nil`s from a sequence or collection, unwrapping the remaining elements.
- [`randomSample(count:)`, `randomSample(count:using:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/RandomSampling.md): Randomly selects a specific number of elements from a collection.
- [`randomStableSample(count:)`, `randomStableSample(count:using:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/RandomSampling.md): Randomly selects a specific number of elements from a collection, preserving their original relative order.
- [`striding(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Stride.md): Returns every nth element of a collection.
- [`suffix(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Suffix.md): Returns the suffix of a collection where all element pass a given predicate.
- [`trimming(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Trim.md): Returns a slice by trimming elements from a collection's start and end.
- [`uniqued()`, `uniqued(on:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Unique.md): The unique elements of a collection, preserving their order.
#### Partial sorting
@@ -40,12 +37,12 @@ Read more about the package, and the intent behind it, in the [announcement on s
#### Other useful operations
- [`chunked(by:)`, `chunked(on:)`, `chunks(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Chunked.md): Eager and lazy operations that break a collection into chunks based on either a binary predicate or when the result of a projection changes or chunks of a given count.
- [`firstNonNil(_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/FirstNonNil.md): Returns the first non-`nil` result from transforming a sequence's elements.
- [`indexed()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Indexed.md): Iterate over tuples of a collection's indices and elements.
- [`interspersed(with:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Intersperse.md): Place a value between every two elements of a sequence.
- [`reductions(_:)`, `reductions(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Reductions.md): Returns all the intermediate states of reducing the elements of a sequence or collection.
- [`split(maxSplits:omittingEmptySubsequences:whereSeparator)`, `split(separator:maxSplits:omittingEmptySubsequences)`](https://github.com/apple/swift-algorithms/blob/main/Guides/LazySplit.md): Lazy versions of the Standard Library's eager operations that split sequences and collections into subsequences separated by the specified separator element.
- [`trimming(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Trim.md): Returns a slice by trimming elements from a collection's start and end.
- [`windows(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Windows.md): Breaks a collection into overlapping subsequences where elements are slices from the original collection.
- [`striding(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Stride.md): Returns every nth element of a collection.
- [`split(maxSplits:omittingEmptySubsequences:whereSeparator)`, `split(separator:maxSplits:omittingEmptySubsequences)`](https://github.com/apple/swift-algorithms/blob/main/Guides/LazySplit.md): Lazy versions of the Standard Library's eager operations that split sequences and collections into subsequences separated by the specified separator element.
## Adding Swift Algorithms as a Dependency
@@ -62,7 +59,7 @@ If you don't want potentially source-breaking package updates,
use this dependency specification instead:
```swift
.package(url: "https://github.com/apple/swift-algorithms", .upToNextMinor(from: "0.1.0")),
.package(url: "https://github.com/apple/swift-algorithms", .upToNextMinor(from: "0.0.1")),
```
Finally, include `"Algorithms"` as a dependency for your executable target:
@@ -71,7 +68,7 @@ Finally, include `"Algorithms"` as a dependency for your executable target:
let package = Package(
// name, platforms, products, etc.
dependencies: [
.package(url: "https://github.com/apple/swift-algorithms", from: "0.1.0"),
.package(url: "https://github.com/apple/swift-algorithms", from: "0.0.1"),
// other dependencies
],
targets: [
+63 -69
View File
@@ -14,12 +14,10 @@ public struct Chain2<Base1: Sequence, Base2: Sequence>
where Base1.Element == Base2.Element
{
/// The first sequence in this chain.
@usableFromInline
internal let base1: Base1
public let base1: Base1
/// The second sequence in this chain.
@usableFromInline
internal let base2: Base2
public let base2: Base2
@inlinable
internal init(base1: Base1, base2: Base2) {
@@ -102,7 +100,7 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
/// Converts an index of `Base1` to the corresponding `Index` by mapping
/// `base1.endIndex` to `base2.startIndex`.
@inlinable
internal func normalizeIndex(_ i: Base1.Index) -> Index {
internal func convertIndex(_ i: Base1.Index) -> Index {
i == base1.endIndex ? Index(second: base2.startIndex) : Index(first: i)
}
@@ -110,7 +108,7 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
public var startIndex: Index {
// if `base1` is empty, this will return `base2.startIndex` - if `base2` is
// also empty, this will correctly equal `base2.endIndex`
normalizeIndex(base1.startIndex)
convertIndex(base1.startIndex)
}
@inlinable
@@ -133,116 +131,109 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
switch i.position {
case let .first(i):
assert(i != base1.endIndex)
return normalizeIndex(base1.index(after: i))
return convertIndex(base1.index(after: i))
case let .second(i):
return Index(second: base2.index(after: i))
}
}
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
guard distance != 0 else { return i }
return distance > 0
? offsetForward(i, by: distance)
: offsetBackward(i, by: -distance)
}
@inlinable
public func index(
_ i: Index,
offsetBy distance: Int,
limitedBy limit: Index
) -> Index? {
if distance >= 0 {
return limit >= i
? offsetForward(i, by: distance, limitedBy: limit)
: offsetForward(i, by: distance)
} else {
return limit <= i
? offsetBackward(i, by: -distance, limitedBy: limit)
: offsetBackward(i, by: -distance)
}
public func index(_ i: Index, offsetBy n: Int) -> Index {
if n == 0 { return i }
return n > 0
? offsetForward(i, by: n, limitedBy: endIndex)!
: offsetBackward(i, by: -n, limitedBy: startIndex)!
}
@inlinable
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
else { fatalError("Index is out of bounds") }
return index
}
@inlinable
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
else { fatalError("Index is out of bounds") }
return index
public func index(
_ i: Index,
offsetBy n: Int,
limitedBy limit: Index
) -> Index? {
if n == 0 { return i }
return n > 0
? offsetForward(i, by: n, limitedBy: limit)
: offsetBackward(i, by: -n, limitedBy: limit)
}
@inlinable
internal func offsetForward(
_ i: Index, by distance: Int, limitedBy limit: Index
_ i: Index, by n: Int, limitedBy limit: Index
) -> Index? {
assert(distance >= 0)
assert(limit >= i)
switch (i.position, limit.position) {
case let (.first(i), .first(limit)):
return base1.index(i, offsetBy: distance, limitedBy: limit)
.map(Index.init(first:))
case let (.first(i), .second(limit)):
if let j = base1.index(i, offsetBy: distance, limitedBy: base1.endIndex) {
if limit >= i {
// `limit` is relevant, so `base2` cannot be reached
return base1.index(i, offsetBy: n, limitedBy: limit)
.map(Index.init(first:))
} else if let j = base1.index(i, offsetBy: n, limitedBy: base1.endIndex) {
// the offset stays within the bounds of `base1`
return normalizeIndex(j)
return convertIndex(j)
} else {
// the offset overflows the bounds of `base1` by `n - d`
let d = base1.distance(from: i, to: base1.endIndex)
return base2.index(base2.startIndex, offsetBy: distance - d, limitedBy: limit)
return Index(second: base2.index(base2.startIndex, offsetBy: n - d))
}
case let (.first(i), .second(limit)):
if let j = base1.index(i, offsetBy: n, limitedBy: base1.endIndex) {
// the offset stays within the bounds of `base1`
return convertIndex(j)
} else {
// the offset overflows the bounds of `base1` by `n - d`
let d = base1.distance(from: i, to: base1.endIndex)
return base2.index(base2.startIndex, offsetBy: n - d, limitedBy: limit)
.map(Index.init(second:))
}
case (.second, .first):
// impossible because `limit >= i`
fatalError()
case let (.second(i), .first):
// `limit` has no effect here
return Index(second: base2.index(i, offsetBy: n))
case let (.second(i), .second(limit)):
return base2.index(i, offsetBy: distance, limitedBy: limit)
return base2.index(i, offsetBy: n, limitedBy: limit)
.map(Index.init(second:))
}
}
@inlinable
internal func offsetBackward(
_ i: Index, by distance: Int, limitedBy limit: Index
_ i: Index, by n: Int, limitedBy limit: Index
) -> Index? {
assert(distance >= 0)
assert(limit <= i)
switch (i.position, limit.position) {
case let (.first(i), .first(limit)):
return base1.index(i, offsetBy: -distance, limitedBy: limit)
return base1.index(i, offsetBy: -n, limitedBy: limit)
.map(Index.init(first:))
case (.first, .second):
// impossible because `limit <= i`
fatalError()
case let (.first(i), .second):
// `limit` has no effect here
return Index(first: base1.index(i, offsetBy: -n))
case let (.second(i), .first(limit)):
if let j = base2.index(i, offsetBy: -distance, limitedBy: base2.startIndex) {
if let j = base2.index(i, offsetBy: -n, limitedBy: base2.startIndex) {
// the offset stays within the bounds of `base2`
return Index(second: j)
} else {
// the offset overflows the bounds of `base2` by `n - d`
let d = base2.distance(from: base2.startIndex, to: i)
return base1.index(base1.endIndex, offsetBy: -(distance - d), limitedBy: limit)
return base1.index(base1.endIndex, offsetBy: -(n - d), limitedBy: limit)
.map(Index.init(first:))
}
case let (.second(i), .second(limit)):
// `limit` is relevant, so `base1` cannot be reached
return base2.index(i, offsetBy: -distance, limitedBy: limit)
.map(Index.init(second:))
if limit <= i {
// `limit` is relevant, so `base1` cannot be reached
return base2.index(i, offsetBy: -n, limitedBy: limit)
.map(Index.init(second:))
} else if let j = base2.index(i, offsetBy: -n, limitedBy: base2.startIndex) {
// the offset stays within the bounds of `base2`
return Index(second: j)
} else {
// the offset overflows the bounds of `base2` by `n - d`
let d = base2.distance(from: base2.startIndex, to: i)
return Index(first: base1.index(base1.endIndex, offsetBy: -(n - d)))
}
}
}
@@ -283,6 +274,9 @@ extension Chain2: BidirectionalCollection
extension Chain2: RandomAccessCollection
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
extension Chain2: Equatable where Base1: Equatable, Base2: Equatable {}
extension Chain2: Hashable where Base1: Hashable, Base2: Hashable {}
//===----------------------------------------------------------------------===//
// chain(_:_:)
//===----------------------------------------------------------------------===//
+23 -13
View File
@@ -11,10 +11,9 @@
/// A collection wrapper that breaks a collection into chunks based on a
/// predicate or projection.
public struct Chunked<Base: Collection, Subject> {
public struct LazyChunked<Base: Collection, Subject> {
/// The collection that this instance provides a view onto.
@usableFromInline
internal let base: Base
public let base: Base
/// The projection function.
@usableFromInline
@@ -45,7 +44,7 @@ public struct Chunked<Base: Collection, Subject> {
}
}
extension Chunked: LazyCollectionProtocol {
extension LazyChunked: LazyCollectionProtocol {
/// A position in a chunked collection.
public struct Index: Comparable {
/// The range corresponding to the chunk at this position.
@@ -106,9 +105,9 @@ extension Chunked: LazyCollectionProtocol {
}
}
extension Chunked.Index: Hashable where Base.Index: Hashable {}
extension LazyChunked.Index: Hashable where Base.Index: Hashable {}
extension Chunked: BidirectionalCollection
extension LazyChunked: BidirectionalCollection
where Base: BidirectionalCollection
{
/// Returns the index in the base collection of the start of the chunk ending
@@ -131,9 +130,6 @@ extension Chunked: BidirectionalCollection
}
}
@available(*, deprecated, renamed: "Chunked")
public typealias LazyChunked<Base: Collection, Subject> = Chunked<Base, Subject>
//===----------------------------------------------------------------------===//
// lazy.chunked(by:)
//===----------------------------------------------------------------------===//
@@ -146,8 +142,8 @@ extension LazyCollectionProtocol {
@inlinable
public func chunked(
by belongInSameGroup: @escaping (Element, Element) -> Bool
) -> Chunked<Elements, Element> {
Chunked(
) -> LazyChunked<Elements, Element> {
LazyChunked(
base: elements,
projection: { $0 },
belongInSameGroup: belongInSameGroup)
@@ -160,8 +156,8 @@ extension LazyCollectionProtocol {
@inlinable
public func chunked<Subject: Equatable>(
on projection: @escaping (Element) -> Subject
) -> Chunked<Elements, Subject> {
Chunked(
) -> LazyChunked<Elements, Subject> {
LazyChunked(
base: elements,
projection: projection,
belongInSameGroup: ==)
@@ -512,6 +508,20 @@ extension Collection {
}
}
// Conditional conformances.
extension ChunkedByCount: Equatable where Base: Equatable {}
// Since we have another stored property of type `Index` on the
// collection, synthesis of `Hashble` conformace would require
// a `Base.Index: Hashable` constraint, so we implement the hasher
// only in terms of `base`. Since the computed index is based on it,
// it should not make a difference here.
extension ChunkedByCount: Hashable where Base: Hashable {
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(base)
}
}
extension ChunkedByCount.Index: Hashable where Base.Index: Hashable {}
// Lazy conditional conformance.
+3 -2
View File
@@ -12,8 +12,7 @@
/// A collection wrapper that generates combinations of a base collection.
public struct Combinations<Base: Collection> {
/// The collection to iterate over for combinations.
@usableFromInline
internal let base: Base
public let base: Base
@usableFromInline
internal let baseCount: Int
@@ -181,6 +180,8 @@ extension Combinations: Sequence {
}
extension Combinations: LazySequenceProtocol where Base: LazySequenceProtocol {}
extension Combinations: Equatable where Base: Equatable {}
extension Combinations: Hashable where Base: Hashable {}
//===----------------------------------------------------------------------===//
// combinations(ofCount:)
-181
View File
@@ -1,181 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// A `Sequence` that iterates over every non-nil element from the original `Sequence`.
public struct CompactedSequence<Base: Sequence, Element>: Sequence
where Base.Element == Element? {
@usableFromInline
let base: Base
@inlinable
init(base: Base) {
self.base = base
}
public struct Iterator: IteratorProtocol {
@usableFromInline
var base: Base.Iterator
@inlinable
init(base: Base.Iterator) {
self.base = base
}
@inlinable
public mutating func next() -> Element? {
while let wrapped = base.next() {
guard let some = wrapped else { continue }
return some
}
return nil
}
}
@inlinable
public func makeIterator() -> Iterator {
return 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 }`.
///
/// let c = [1, nil, 2, 3, nil]
/// for num in c.compacted() {
/// print(num)
/// }
/// // 1
/// // 2
/// // 3
///
/// - Returns: A `Sequence` where the element is the unwrapped original
/// element and iterates over every non-nil element from the original
/// `Sequence`.
///
/// Complexity: O(1)
@inlinable
public func compacted<Unwrapped>() -> CompactedSequence<Self, Unwrapped>
where Element == Unwrapped? {
CompactedSequence(base: self)
}
}
/// A `Collection` that iterates over every non-nil element from the original `Collection`.
public struct CompactedCollection<Base: Collection, Element>: Collection
where Base.Element == Element? {
@usableFromInline
let base: Base
@inlinable
init(base: Base) {
self.base = base
let idx = base.firstIndex(where: { $0 != nil }) ?? base.endIndex
self.startIndex = Index(base: idx)
}
public struct Index {
@usableFromInline
let base: Base.Index
@inlinable
init(base: Base.Index) {
self.base = base
}
}
public var startIndex: Index
@inlinable
public var endIndex: Index { Index(base: base.endIndex) }
@inlinable
public subscript(position: Index) -> Element {
base[position.base]!
}
@inlinable
public func index(after i: Index) -> Index {
precondition(i != endIndex, "Index out of bounds")
let baseIdx = base.index(after: i.base)
guard let idx = base[baseIdx...].firstIndex(where: { $0 != nil })
else { return endIndex }
return Index(base: idx)
}
}
extension CompactedCollection: BidirectionalCollection
where Base: BidirectionalCollection {
@inlinable
public func index(before i: Index) -> Index {
precondition(i != startIndex, "Index out of bounds")
guard let idx =
base[startIndex.base..<i.base]
.lastIndex(where: { $0 != nil })
else { fatalError("Index out of bounds") }
return Index(base: idx)
}
}
extension CompactedCollection.Index: Comparable {
@inlinable
public static func < (lhs: CompactedCollection.Index,
rhs: CompactedCollection.Index) -> Bool {
lhs.base < rhs.base
}
}
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 }`.
///
/// let c = [1, nil, 2, 3, nil]
/// for num in c.compacted() {
/// print(num)
/// }
/// // 1
/// // 2
/// // 3
///
/// - Returns: A `Collection` where the element is the unwrapped original
/// element and iterates over every non-nil element from the original
/// `Collection`.
///
/// Complexity: O(*n*) where *n* is the number of elements in the
/// original `Collection`.
@inlinable
public func compacted<Unwrapped>() -> CompactedCollection<Self, Unwrapped>
where Element == Unwrapped? {
CompactedCollection(base: self)
}
}
//===----------------------------------------------------------------------===//
// Protocol Conformances
//===----------------------------------------------------------------------===//
extension CompactedSequence: LazySequenceProtocol
where Base: LazySequenceProtocol {}
extension CompactedCollection: LazySequenceProtocol
where Base: LazySequenceProtocol {}
extension CompactedCollection: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
+5 -112
View File
@@ -12,8 +12,7 @@
/// A collection wrapper that repeats the elements of a base collection.
public struct Cycle<Base: Collection> {
/// The collection to repeat.
@usableFromInline
internal let base: Base
public let base: Base
@inlinable
internal init(base: Base) {
@@ -25,10 +24,10 @@ extension Cycle: Sequence {
/// The iterator for a `Cycle` sequence.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal let base: Base
let base: Base
@usableFromInline
internal var current: Base.Index
var current: Base.Index
@inlinable
internal init(base: Base) {
@@ -57,112 +56,6 @@ extension Cycle: Sequence {
extension Cycle: 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.
@usableFromInline
internal let product: Product2<Range<Int>, Base>
@inlinable
internal init(base: Base, times: Int) {
self.product = Product2(0..<times, base)
}
}
extension FiniteCycle: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazyCollectionProtocol { }
extension FiniteCycle: Collection {
public typealias Element = Base.Element
public struct Index: Comparable {
/// The index corresponding to the Product2 index at this position.
@usableFromInline
internal let productIndex: Product2<Range<Int>, Base>.Index
@inlinable
internal init(_ productIndex: Product2<Range<Int>, Base>.Index) {
self.productIndex = productIndex
}
@inlinable
public static func == (lhs: Index, rhs: Index) -> Bool {
lhs.productIndex == rhs.productIndex
}
@inlinable
public static func < (lhs: Index, rhs: Index) -> Bool {
lhs.productIndex < rhs.productIndex
}
}
@inlinable
public var startIndex: Index {
Index(product.startIndex)
}
@inlinable
public var endIndex: Index {
Index(product.endIndex)
}
@inlinable
public subscript(_ index: Index) -> Element {
product[index.productIndex].1
}
@inlinable
public func index(after i: Index) -> Index {
let productIndex = product.index(after: i.productIndex)
return Index(productIndex)
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
product.distance(from: start.productIndex, to: end.productIndex)
}
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
let productIndex = product.index(i.productIndex, offsetBy: distance)
return Index(productIndex)
}
@inlinable
public func index(
_ i: Index,
offsetBy distance: Int,
limitedBy limit: Index
) -> Index? {
guard let productIndex = product.index(i.productIndex,
offsetBy: distance,
limitedBy: limit.productIndex) else {
return nil
}
return Index(productIndex)
}
@inlinable
public var count: Int {
product.count
}
}
extension FiniteCycle: BidirectionalCollection
where Base: BidirectionalCollection {
@inlinable
public func index(before i: Index) -> Index {
let productIndex = product.index(before: i.productIndex)
return Index(productIndex)
}
}
extension FiniteCycle: RandomAccessCollection
where Base: RandomAccessCollection {}
//===----------------------------------------------------------------------===//
// cycled()
//===----------------------------------------------------------------------===//
@@ -216,7 +109,7 @@ extension Collection {
///
/// - Complexity: O(1)
@inlinable
public func cycled(times: Int) -> FiniteCycle<Self> {
FiniteCycle(base: self, times: times)
public func cycled(times: Int) -> FlattenSequence<Repeated<Self>> {
repeatElement(self, count: times).joined()
}
}
+7 -22
View File
@@ -14,30 +14,15 @@
//===----------------------------------------------------------------------===//
public extension Sequence {
/// Returns the first non-`nil` result obtained from applying the given
/// transformation to the elements of the sequence.
///
/// let strings = ["three", "3.14", "-5", "2"]
/// if let firstInt = strings.firstNonNil({ Int($0) }) {
/// print(firstInt)
/// // -5
/// }
///
/// - Parameter transform: A closure that takes an element of the sequence as
/// its argument and returns an optional transformed value.
/// - Returns: The first non-`nil` return value of the transformation, or
/// `nil` if no transformation is successful.
///
/// - Complexity: O(*n*), where *n* is the number of elements at the start of
/// the sequence that result in `nil` when applying the transformation.
/// Returns the first element in `self` that `transform` maps to a `.some`.
func firstNonNil<Result>(
_ transform: (Element) throws -> Result?
) rethrows -> Result? {
for value in self {
if let value = try transform(value) {
return value
}
for value in self {
if let value = try transform(value) {
return value
}
}
return nil
}
return nil
}
}
+3 -2
View File
@@ -16,8 +16,7 @@ public struct Indexed<Base: Collection> {
public typealias Element = (index: Base.Index, element: Base.Element)
/// The base collection.
@usableFromInline
internal let base: Base
public let base: Base
@inlinable
internal init(base: Base) {
@@ -72,6 +71,8 @@ extension Indexed: BidirectionalCollection where Base: BidirectionalCollection {
extension Indexed: RandomAccessCollection where Base: RandomAccessCollection {}
extension Indexed: LazySequenceProtocol where Base: LazySequenceProtocol {}
extension Indexed: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
extension Indexed: Equatable where Base: Equatable {}
extension Indexed: Hashable where Base: Hashable {}
//===----------------------------------------------------------------------===//
// indexed()
+3 -5
View File
@@ -78,8 +78,7 @@ extension MutableCollection
/// A sequence of all the permutations of a collection's elements.
public struct Permutations<Base: Collection> {
/// The base collection to iterate over for permutations.
@usableFromInline
internal let base: Base
public let base: Base
@usableFromInline
internal let baseCount: Int
@@ -138,7 +137,7 @@ extension Permutations: Sequence {
/// The iterator for a `Permutations` instance.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal let base: Base
internal var base: Base
@usableFromInline
internal let baseCount: Int
@@ -398,8 +397,7 @@ extension Collection {
/// `uniquePermutations` methods on your collection.
public struct UniquePermutations<Base: Collection> {
/// The base collection to iterate over for permutations.
@usableFromInline
internal let base: Base
public let base: Base
@usableFromInline
internal var indexes: [Base.Index]
+6 -11
View File
@@ -12,12 +12,9 @@
/// A sequence that represents the product of two sequences' elements.
public struct Product2<Base1: Sequence, Base2: Collection> {
/// The outer sequence in the product.
@usableFromInline
internal let base1: Base1
public let base1: Base1
/// The inner sequence in the product.
@usableFromInline
internal let base2: Base2
public let base2: Base2
@inlinable
internal init(_ base1: Base1, _ base2: Base2) {
@@ -27,8 +24,6 @@ public struct Product2<Base1: Sequence, Base2: Collection> {
}
extension Product2: Sequence {
public typealias Element = (Base1.Element, Base2.Element)
/// The iterator for a `Product2` sequence.
public struct Iterator: IteratorProtocol {
@usableFromInline
@@ -49,8 +44,7 @@ extension Product2: Sequence {
}
@inlinable
public mutating func next() -> (Base1.Element,
Base2.Element)? {
public mutating func next() -> (Base1.Element, Base2.Element)? {
// This is the initial state, where i1.next() has never
// been called, or the final state, where i1.next() has
// already returned nil.
@@ -127,8 +121,7 @@ extension Product2: Collection where Base1: Collection {
}
@inlinable
public subscript(position: Index) -> (Base1.Element,
Base2.Element) {
public subscript(position: Index) -> (Base1.Element, Base2.Element) {
(base1[position.i1], base2[position.i2])
}
@@ -440,6 +433,8 @@ extension Product2: RandomAccessCollection
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
extension Product2.Index: Hashable where Base1.Index: Hashable, Base2.Index: Hashable {}
extension Product2: Equatable where Base1: Equatable, Base2: Equatable {}
extension Product2: Hashable where Base1: Hashable, Base2: Hashable {}
//===----------------------------------------------------------------------===//
// product(_:_:)
+18
View File
@@ -269,4 +269,22 @@ extension StrideCollection: BidirectionalCollection
}
extension StrideCollection: RandomAccessCollection where Base: RandomAccessCollection {}
extension StrideCollection: Equatable where Base.Element: Equatable {
@inlinable
public static func == (lhs: StrideCollection, rhs: StrideCollection) -> Bool {
lhs.elementsEqual(rhs, by: ==)
}
}
extension StrideCollection: Hashable where Base.Element: Hashable {
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(stride)
for element in self {
hasher.combine(element)
}
}
}
extension StrideCollection.Index: Hashable where Base.Index: Hashable {}
+7 -82
View File
@@ -9,82 +9,25 @@
//
//===----------------------------------------------------------------------===//
/// A sequence wrapper that leaves out duplicate elements of a base sequence.
public struct Uniqued<Base: Sequence, Subject: Hashable> {
/// The base collection.
@usableFromInline
internal let base: Base
/// The projection function.
@usableFromInline
internal let projection: (Base.Element) -> Subject
@usableFromInline
internal init(base: Base, projection: @escaping (Base.Element) -> Subject) {
self.base = base
self.projection = projection
}
}
extension Uniqued: Sequence {
/// The iterator for a `Uniqued` sequence.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var base: Base.Iterator
@usableFromInline
internal let projection: (Base.Element) -> Subject
@usableFromInline
internal var seen: Set<Subject> = []
@usableFromInline
internal init(
base: Base.Iterator,
projection: @escaping (Base.Element) -> Subject
) {
self.base = base
self.projection = projection
}
@inlinable
public mutating func next() -> Base.Element? {
while let element = base.next() {
if seen.insert(projection(element)).inserted {
return element
}
}
return nil
}
}
@inlinable
public func makeIterator() -> Iterator {
Iterator(base: base.makeIterator(), projection: projection)
}
}
extension Uniqued: LazySequenceProtocol where Base: LazySequenceProtocol {}
//===----------------------------------------------------------------------===//
// uniqued()
//===----------------------------------------------------------------------===//
extension Sequence where Element: Hashable {
/// Returns a sequence with only the unique elements of this sequence, in the
/// Returns an array with only the unique elements of this sequence, in the
/// order of the first occurrence of each unique element.
///
/// let animals = ["dog", "pig", "cat", "ox", "dog", "cat"]
/// let uniqued = animals.uniqued()
/// print(Array(uniqued))
/// print(uniqued)
/// // Prints '["dog", "pig", "cat", "ox"]'
///
/// - Returns: A sequence with only the unique elements of this sequence.
/// - Returns: An array with only the unique elements of this sequence.
/// .
/// - Complexity: O(1).
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func uniqued() -> Uniqued<Self, Element> {
Uniqued(base: self, projection: { $0 })
public func uniqued() -> [Element] {
uniqued(on: { $0 })
}
}
@@ -97,7 +40,7 @@ extension Sequence {
/// first characters:
///
/// let animals = ["dog", "pig", "cat", "ox", "cow", "owl"]
/// let uniqued = animals.uniqued(on: { $0.first })
/// let uniqued = animals.uniqued(on: {$0.first})
/// print(uniqued)
/// // Prints '["dog", "pig", "cat", "ox"]'
///
@@ -124,21 +67,3 @@ extension Sequence {
return result
}
}
//===----------------------------------------------------------------------===//
// lazy.uniqued()
//===----------------------------------------------------------------------===//
extension LazySequenceProtocol {
/// Returns a lazy sequence with the unique elements of this sequence (as
/// determined by the given projection), in the order of the first occurrence
/// of each unique element.
///
/// - Complexity: O(1).
@inlinable
public func uniqued<Subject: Hashable>(
on projection: @escaping (Element) -> Subject
) -> Uniqued<Self, Subject> {
Uniqued(base: self, projection: projection)
}
}
+4 -5
View File
@@ -47,11 +47,8 @@ extension Collection {
/// A collection wrapper that presents a sliding window over the elements of
/// a collection.
public struct Windows<Base: Collection> {
@usableFromInline
internal let base: Base
@usableFromInline
internal let size: Int
public let base: Base
public let size: Int
@usableFromInline
internal var firstUpperBound: Base.Index?
@@ -350,4 +347,6 @@ 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: Equatable where Base: Equatable {}
extension Windows: Hashable where Base: Hashable, Base.Index: Hashable {}
extension Windows.Index: Hashable where Base.Index: Hashable {}
@@ -1,44 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import XCTest
import Algorithms
final class CompactedTests: XCTestCase {
let tests: [[Int?]] =
[nil, nil, nil, 0, 1, 2]
.uniquePermutations(ofCount: 0...)
.map(Array.init)
func testCompactedCompacted() {
for collection in self.tests {
let seq = AnySequence(collection)
XCTAssertEqualSequences(
seq.compactMap({ $0 }), seq.compacted())
XCTAssertEqualSequences(
collection.compactMap({ $0 }), collection.compacted())
}
}
func testCompactedBidirectionalCollection() {
for array in self.tests {
XCTAssertEqualSequences(array.compactMap({ $0 }).reversed(),
array.compacted().reversed())
}
}
func testCollectionTraversals() {
for array in self.tests {
validateIndexTraversals(array.compacted())
}
}
}
+7 -49
View File
@@ -19,70 +19,28 @@ final class CycleTests: XCTestCase {
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],
cycle.prefix(20)
)
}
func testCycleClosedRangePrefix() {
let a = Array((0..<17).cycled().prefix(10_000))
XCTAssertEqual(10_000, a.count)
}
func testEmptyCycle() {
let empty = Array("".cycled())
XCTAssert(empty.isEmpty)
}
func testCycleLazy() {
XCTAssertLazySequence((1...4).lazy.cycled())
}
func testRepeated() {
let repeats = (1...4).cycled(times: 3)
XCTAssertEqualSequences(
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],
repeats)
}
func testRepeatedClosedRange() {
let repeats = Array((1..<5).cycled(times: 2500))
XCTAssertEqual(10_000, repeats.count)
}
func testRepeatedEmptyCollection() {
let empty1 = Array("".cycled(times: 100))
XCTAssert(empty1.isEmpty)
}
func testRepeatedZeroTimesCycle() {
let empty2 = Array("Hello".cycled(times: 0))
XCTAssert(empty2.isEmpty)
}
func testRepeatedLazy() {
XCTAssertLazySequence((1...4).lazy.cycled(times: 3))
}
func testRepeatedIndexMethods() {
let cycle = (1..<5).cycled(times: 2)
let startIndex = cycle.startIndex
var nextIndex = cycle.index(after: startIndex)
XCTAssertEqual(cycle.distance(from: startIndex, to: nextIndex), 1)
nextIndex = cycle.index(nextIndex, offsetBy: 5)
XCTAssertEqual(cycle.distance(from: startIndex, to: nextIndex), 6)
nextIndex = cycle.index(nextIndex, offsetBy: 2, limitedBy: cycle.endIndex)!
XCTAssertEqual(cycle.distance(from: startIndex, to: nextIndex), 8)
let outOfBounds = cycle.index(nextIndex, offsetBy: 1,
limitedBy: cycle.endIndex)
XCTAssertNil(outOfBounds)
let previousIndex = cycle.index(before: nextIndex)
XCTAssertEqual(cycle.distance(from: startIndex, to: previousIndex), 7)
}
func testRepeatedCount() {
let cycle = (1..<5).cycled(times: 2)
XCTAssertEqual(cycle.count, 8)
func testCycleLazy() {
XCTAssertLazySequence((1...4).lazy.cycled())
}
}
@@ -64,6 +64,19 @@ final class StridingTests: XCTestCase {
// a.index(after: a.endIndex) // Precondition failed: Advancing past end index
}
func testStrideCompositionEquivalence() {
let a = (0...10)
XCTAssertEqualSequences(a.striding(by: 6), a.striding(by: 2).striding(by: 3))
XCTAssertTrue(a.striding(by: 6) == a.striding(by: 2).striding(by: 3))
XCTAssert(type(of: a.striding(by: 2).striding(by: 3)) == StrideCollection<ClosedRange<Int>>.self)
}
func testEquality() {
let a = [1, 2, 3, 4, 5].striding(by: 2)
let b = [1, 0, 3, 0, 5].striding(by: 2)
XCTAssertEqual(a, b)
}
func testStrideLast() {
XCTAssertEqual((1...10).striding(by: 2).last, 9) // 1, 3, 5, 7, 9
XCTAssertEqual((1...10).striding(by: 3).last, 10) // 1, 4, 7, 10
+2 -21
View File
@@ -17,13 +17,10 @@ final class UniqueTests: XCTestCase {
let a = repeatElement(1...10, count: 15).joined().shuffled()
let b = a.uniqued()
XCTAssertEqual(b.sorted(), Set(a).sorted())
XCTAssertEqual(10, Array(b).count)
XCTAssertEqual(10, b.count)
let c: [Int] = []
XCTAssertEqualSequences(c.uniqued(), [])
let d = Array(repeating: 1, count: 10)
XCTAssertEqualSequences(d.uniqued(), [1])
XCTAssertEqual(c.uniqued(), [])
}
func testUniqueOn() {
@@ -33,21 +30,5 @@ final class UniqueTests: XCTestCase {
let c: [Int] = []
XCTAssertEqual(c.uniqued(on: { $0.bitWidth }), [])
let d = Array(repeating: "Andromeda", count: 10)
XCTAssertEqualSequences(d.uniqued(on: { $0.first }), ["Andromeda"])
}
func testLazyUniqueOn() {
let a = ["Albemarle", "Abeforth", "Astrology", "Brandywine", "Beatrice", "Axiom"]
let b = a.lazy.uniqued(on: { $0.first })
XCTAssertEqualSequences(b, ["Albemarle", "Brandywine"])
XCTAssertLazySequence(b)
let c: [Int] = []
XCTAssertEqualSequences(c.lazy.uniqued(on: { $0.bitWidth }), [])
let d = Array(repeating: "Andromeda", count: 10)
XCTAssertEqualSequences(d.lazy.uniqued(on: { $0.first }), ["Andromeda"])
}
}