mirror of
https://github.com/apple/swift-algorithms
synced 2026-11-29 04:44:21 +00:00
Compare commits
15
Commits
reductions-into
...
0.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
36bcc5581b | ||
|
|
31d600a4f1 | ||
|
|
0e44ceb7bb | ||
|
|
78dd4b5b93 | ||
|
|
abc5559ef6 | ||
|
|
bcdbac800a | ||
|
|
718220d0f8 | ||
|
|
551b4af927 | ||
|
|
dca25448e0 | ||
|
|
1639c1e2c3 | ||
|
|
a61c3db4fb | ||
|
|
198eee004e | ||
|
|
4cca4895cc | ||
|
|
001247f8a5 | ||
|
|
0065c60a22 |
No files matched your search
+72
-2
@@ -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
|
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
|
`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
|
package updates, you can specify your package dependency using
|
||||||
`.upToNextMinor(from: "0.0.1")` as the requirement.
|
`.upToNextMinor(from: "0.1.0")` as the requirement.
|
||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
@@ -16,6 +16,59 @@ 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
|
## [0.0.3] - 2021-02-26
|
||||||
|
|
||||||
### Additions
|
### Additions
|
||||||
@@ -96,7 +149,9 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
|
|||||||
|
|
||||||
<!-- Link references for releases -->
|
<!-- Link references for releases -->
|
||||||
|
|
||||||
[Unreleased]: https://github.com/apple/swift-algorithms/compare/0.0.3...HEAD
|
[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
|
||||||
[0.0.3]: https://github.com/apple/swift-algorithms/compare/0.0.2...0.0.3
|
[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.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
|
[0.0.1]: https://github.com/apple/swift-algorithms/releases/tag/0.0.1
|
||||||
@@ -107,24 +162,37 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
|
|||||||
[#9]: https://github.com/apple/swift-algorithms/pull/9
|
[#9]: https://github.com/apple/swift-algorithms/pull/9
|
||||||
[#20]: https://github.com/apple/swift-algorithms/pull/20
|
[#20]: https://github.com/apple/swift-algorithms/pull/20
|
||||||
[#24]: https://github.com/apple/swift-algorithms/pull/24
|
[#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
|
[#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
|
[#51]: https://github.com/apple/swift-algorithms/pull/51
|
||||||
[#54]: https://github.com/apple/swift-algorithms/pull/54
|
[#54]: https://github.com/apple/swift-algorithms/pull/54
|
||||||
[#56]: https://github.com/apple/swift-algorithms/pull/56
|
[#56]: https://github.com/apple/swift-algorithms/pull/56
|
||||||
[#65]: https://github.com/apple/swift-algorithms/pull/65
|
[#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
|
[#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 -->
|
<!-- Link references for contributors -->
|
||||||
|
|
||||||
[AustinConlon]: https://github.com/apple/swift-algorithms/commits?author=AustinConlon
|
[AustinConlon]: https://github.com/apple/swift-algorithms/commits?author=AustinConlon
|
||||||
[benrimmington]: https://github.com/apple/swift-algorithms/commits?author=benrimmington
|
[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
|
[danielctull]: https://github.com/apple/swift-algorithms/commits?author=danielctull
|
||||||
[dhruvshah8]: https://github.com/apple/swift-algorithms/commits?author=dhruvshah8
|
[dhruvshah8]: https://github.com/apple/swift-algorithms/commits?author=dhruvshah8
|
||||||
[egorzhdan]: https://github.com/apple/swift-algorithms/commits?author=egorzhdan
|
[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
|
[IanKeen]: https://github.com/apple/swift-algorithms/commits?author=IanKeen
|
||||||
[iSame7]: https://github.com/apple/swift-algorithms/commits?author=iSame7
|
[iSame7]: https://github.com/apple/swift-algorithms/commits?author=iSame7
|
||||||
[karwa]: https://github.com/apple/swift-algorithms/commits?author=karwa
|
[karwa]: https://github.com/apple/swift-algorithms/commits?author=karwa
|
||||||
[kylemacomber]: https://github.com/apple/swift-algorithms/commits?author=kylemacomber
|
[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
|
[LucianoPAlmeida]: https://github.com/apple/swift-algorithms/commits?author=LucianoPAlmeida
|
||||||
[markuswntr]: https://github.com/apple/swift-algorithms/commits?author=markuswntr
|
[markuswntr]: https://github.com/apple/swift-algorithms/commits?author=markuswntr
|
||||||
[mdznr]: https://github.com/apple/swift-algorithms/commits?author=mdznr
|
[mdznr]: https://github.com/apple/swift-algorithms/commits?author=mdznr
|
||||||
@@ -133,6 +201,7 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
|
|||||||
[nordicio]: https://github.com/apple/swift-algorithms/commits?author=nordicio
|
[nordicio]: https://github.com/apple/swift-algorithms/commits?author=nordicio
|
||||||
[ollieatkinson]: https://github.com/apple/swift-algorithms/commits?author=ollieatkinson
|
[ollieatkinson]: https://github.com/apple/swift-algorithms/commits?author=ollieatkinson
|
||||||
[pmtao]: https://github.com/apple/swift-algorithms/commits?author=pmtao
|
[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
|
[rakaramos]: https://github.com/apple/swift-algorithms/commits?author=rakaramos
|
||||||
[rockbruno]: https://github.com/apple/swift-algorithms/commits?author=rockbruno
|
[rockbruno]: https://github.com/apple/swift-algorithms/commits?author=rockbruno
|
||||||
[Roshankumar350]: https://github.com/apple/swift-algorithms/commits?author=Roshankumar350
|
[Roshankumar350]: https://github.com/apple/swift-algorithms/commits?author=Roshankumar350
|
||||||
@@ -140,3 +209,4 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
|
|||||||
[sidepelican]: https://github.com/apple/swift-algorithms/commits?author=sidepelican
|
[sidepelican]: https://github.com/apple/swift-algorithms/commits?author=sidepelican
|
||||||
[stephentyrone]: https://github.com/apple/swift-algorithms/commits?author=stephentyrone
|
[stephentyrone]: https://github.com/apple/swift-algorithms/commits?author=stephentyrone
|
||||||
[timvermeulen]: https://github.com/apple/swift-algorithms/commits?author=timvermeulen
|
[timvermeulen]: https://github.com/apple/swift-algorithms/commits?author=timvermeulen
|
||||||
|
[toddthomas]: https://github.com/apple/swift-algorithms/commits?author=toddthomas
|
||||||
+3
-3
@@ -76,15 +76,15 @@ extension Collection {
|
|||||||
extension LazyCollectionProtocol {
|
extension LazyCollectionProtocol {
|
||||||
public func chunked(
|
public func chunked(
|
||||||
by belongInSameGroup: @escaping (Element, Element) -> Bool
|
by belongInSameGroup: @escaping (Element, Element) -> Bool
|
||||||
) -> LazyChunked<Elements>
|
) -> Chunked<Elements>
|
||||||
|
|
||||||
public func chunked<Subject: Equatable>(
|
public func chunked<Subject: Equatable>(
|
||||||
on projection: @escaping (Element) -> Subject
|
on projection: @escaping (Element) -> Subject
|
||||||
) -> LazyChunked<Elements>
|
) -> Chunked<Elements>
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
The `LazyChunked` type is bidirectional when the wrapped collection is
|
The `Chunked` type is bidirectional when the wrapped collection is
|
||||||
bidirectional.
|
bidirectional.
|
||||||
|
|
||||||
### Complexity
|
### Complexity
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# 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.
|
||||||
+9
-8
@@ -16,9 +16,9 @@ for x in (1...3).cycled(times: 3) {
|
|||||||
// Prints 1 through 3 three times
|
// Prints 1 through 3 three times
|
||||||
```
|
```
|
||||||
|
|
||||||
`cycled(times:)` combines two other existing standard library functions
|
`cycled(times:)` provides a more expressive way of repeating a
|
||||||
(`repeatElement` and `joined`) to provide a more expressive way of repeating a
|
collection's elements a limited number of times than
|
||||||
collection's elements a limited number of times.
|
combining `repeatElement(_:count:)` and `joined()`.
|
||||||
|
|
||||||
## Detailed Design
|
## Detailed Design
|
||||||
|
|
||||||
@@ -28,7 +28,7 @@ Two new methods are added to collections:
|
|||||||
extension Collection {
|
extension Collection {
|
||||||
func cycled() -> Cycle<Self>
|
func cycled() -> Cycle<Self>
|
||||||
|
|
||||||
func cycled(times: Int) -> FlattenSequence<Repeated<Self>>
|
func cycled(times: Int) -> FiniteCycle<Self>
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -36,9 +36,10 @@ The new `Cycle` type is a sequence only, given that the `Collection` protocol
|
|||||||
design makes infinitely large types impossible/impractical. `Cycle` also
|
design makes infinitely large types impossible/impractical. `Cycle` also
|
||||||
conforms to `LazySequenceProtocol` when the base type conforms.
|
conforms to `LazySequenceProtocol` when the base type conforms.
|
||||||
|
|
||||||
Note that despite its name, the returned `FlattenSequence` will always have
|
The `FiniteCycle` type always has `Collection` conformance, with
|
||||||
`Collection` conformance, and will have `BidirectionalCollection` conformance
|
`BidirectionalCollection` conformance
|
||||||
when called on a bidirectional collection.
|
when called on a bidirectional collection. `FiniteCycle` also
|
||||||
|
conforms to `LazyCollectionProtocol` when the base type conforms.
|
||||||
|
|
||||||
### Complexity
|
### Complexity
|
||||||
|
|
||||||
@@ -61,4 +62,4 @@ anything that matches the `cycled(times:)` behavior.
|
|||||||
`cycled(times:)` here.
|
`cycled(times:)` here.
|
||||||
|
|
||||||
**Python:** Python’s `itertools` includes a `cycle` method, which caches the
|
**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.
|
||||||
+60
-18
@@ -2,23 +2,48 @@
|
|||||||
|
|
||||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/FirstNonNil.swift) |
|
[[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)]
|
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/FirstNonNilTests.swift)]
|
||||||
|
|
||||||
Retrieves the first `.some` encountered while applying the given transform.
|
Returns the first non-`nil` result obtained from applying the given
|
||||||
|
transformation to the elements of the sequence.
|
||||||
This operation is available through the `firstNonNil(_:)` method on any sequence.
|
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
let value = ["A", "B", "10"].firstNonNil { Int($0) }
|
let strings = ["three", "3.14", "-5", "2"]
|
||||||
// value == .some(10)
|
if let firstInt = strings.firstNonNil({ Int($0) }) {
|
||||||
//
|
print(firstInt)
|
||||||
let noValue = ["A", "B", "C"].firstNonNil { Int($0) }
|
// -5
|
||||||
// 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:
|
||||||
|
|
||||||
This method is analogous to `first(where:)` in how it only consumes values until
|
```swift
|
||||||
a `.some` is found, unlike using lazy operators, which will load any sequence into a collection
|
let strings = ["three", "3.14", "-5", "2"]
|
||||||
before evaluating its transforms lazily.
|
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 {
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## Detailed Design
|
## Detailed Design
|
||||||
|
|
||||||
@@ -27,17 +52,34 @@ protocol:
|
|||||||
|
|
||||||
```swift
|
```swift
|
||||||
public extension Sequence {
|
public extension Sequence {
|
||||||
func firstNonNil<Result>(_ transform: (Element) throws -> Result?)
|
func firstNonNil<Result>(
|
||||||
rethrows -> 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
|
### Naming
|
||||||
|
|
||||||
This method’s name was selected for its comprehensibility.
|
Some alternative names were considered:
|
||||||
|
|
||||||
|
* `compactMapFirst(_:)`
|
||||||
|
* `first(mapping:)`
|
||||||
|
* `firstSome(_:)`
|
||||||
|
* `firstMap(_:)`
|
||||||
|
|
||||||
### Comparison with other languages
|
### Comparison with other languages
|
||||||
|
|
||||||
**Scala**: Scala provides a `collectFirst` function that finds the first element
|
**Haskell**: Haskell includes the `firstJust` method, which has the same
|
||||||
in a collection for which a partial function is defined.
|
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.
|
||||||
+6
-11
@@ -3,21 +3,16 @@
|
|||||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Reductions.swift) |
|
[[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)]
|
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/ReductionsTests.swift)]
|
||||||
|
|
||||||
Produces a sequence of values.
|
Produces all the intermediate results of reducing a sequence's elements using a closure.
|
||||||
|
|
||||||
This has the behaviour of reduce, but also returns all intermediate results.
|
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
let exclusiveRunningTotal = (1...5).reductions(0, +)
|
let exclusiveRunningTotal = (1...5).reductions(0, +)
|
||||||
print(exclusiveRunningTotal)
|
print(exclusiveRunningTotal)
|
||||||
// prints [0, 1, 3, 6, 10, 15]
|
// prints [0, 1, 3, 6, 10, 15]
|
||||||
|
|
||||||
var value = 0
|
let intoRunningTotal = (1...5).reductions(into: 0, +=)
|
||||||
let intoRunningTotal = (1...5).reductions(into: &value, +=)
|
|
||||||
print(intoRunningTotal)
|
print(intoRunningTotal)
|
||||||
// prints [0, 1, 3, 6, 10, 15]
|
// prints [0, 1, 3, 6, 10, 15]
|
||||||
print(value)
|
|
||||||
// prints 15
|
|
||||||
|
|
||||||
let inclusiveRunningTotal = (1...5).reductions(+)
|
let inclusiveRunningTotal = (1...5).reductions(+)
|
||||||
print(inclusiveRunningTotal)
|
print(inclusiveRunningTotal)
|
||||||
@@ -38,7 +33,7 @@ extension LazySequenceProtocol {
|
|||||||
) -> ExclusiveReductions<Result, Self>
|
) -> ExclusiveReductions<Result, Self>
|
||||||
|
|
||||||
public func reductions<Result>(
|
public func reductions<Result>(
|
||||||
into initial: inout Result,
|
into initial: Result,
|
||||||
_ transform: @escaping (inout Result, Element) -> Void
|
_ transform: @escaping (inout Result, Element) -> Void
|
||||||
) -> ExclusiveReductions<Result, Self>
|
) -> ExclusiveReductions<Result, Self>
|
||||||
|
|
||||||
@@ -57,7 +52,7 @@ extension Sequence {
|
|||||||
) rethrows -> [Result]
|
) rethrows -> [Result]
|
||||||
|
|
||||||
public func reductions<Result>(
|
public func reductions<Result>(
|
||||||
into initial: inout Result,
|
into initial: Result,
|
||||||
_ transform: (inout Result, Element) throws -> Void
|
_ transform: (inout Result, Element) throws -> Void
|
||||||
) rethrows -> [Result]
|
) rethrows -> [Result]
|
||||||
|
|
||||||
@@ -115,7 +110,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
|
[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
|
[Kyle Macomber]: https://github.com/apple/swift-algorithms/issues/25#issuecomment-709317894
|
||||||
|
|
||||||
### Comparison with other langauges
|
### Comparison with other languages
|
||||||
|
|
||||||
**C++:** As of C++17, the `<algorithm>` library includes both
|
**C++:** As of C++17, the `<algorithm>` library includes both
|
||||||
[`exclusive_scan`][C++ Exclusive] and [`inclusive_scan`][C++ Inclusive]
|
[`exclusive_scan`][C++ Exclusive] and [`inclusive_scan`][C++ Inclusive]
|
||||||
@@ -127,7 +122,7 @@ functions.
|
|||||||
`Traversable` type, which is akin to Swift's `Sequence`.
|
`Traversable` type, which is akin to Swift's `Sequence`.
|
||||||
|
|
||||||
**Python:** Python’s `itertools` includes an `accumulate` method. In version
|
**Python:** Python’s `itertools` includes an `accumulate` method. In version
|
||||||
3.3, a function paramenter was added. Version 3.8 added the optional initial
|
3.3, a function parameter was added. Version 3.8 added the optional initial
|
||||||
parameter.
|
parameter.
|
||||||
|
|
||||||
**[Rust][Rust]:** Rust provides a `scan` function.
|
**[Rust][Rust]:** Rust provides a `scan` function.
|
||||||
|
|||||||
+1
-1
@@ -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.
|
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 conscise code, which is more aligned with other programming
|
Besides that, the root `trim` leads to clearer, more concise code, which is more aligned with other programming
|
||||||
languages:
|
languages:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
|
|||||||
+14
-7
@@ -5,7 +5,7 @@
|
|||||||
|
|
||||||
Methods to strip repeated elements from a sequence or collection.
|
Methods to strip repeated elements from a sequence or collection.
|
||||||
|
|
||||||
The `uniqued()` method returns an array, dropping duplicate elements
|
The `uniqued()` method returns a sequence, dropping duplicate elements
|
||||||
from a sequence. The `uniqued(on:)` method does the same, using
|
from a sequence. The `uniqued(on:)` method does the same, using
|
||||||
the result of the given closure to determine the "uniqueness" of each
|
the result of the given closure to determine the "uniqueness" of each
|
||||||
element.
|
element.
|
||||||
@@ -14,29 +14,36 @@ element.
|
|||||||
let numbers = [1, 2, 3, 3, 2, 3, 3, 2, 2, 2, 1]
|
let numbers = [1, 2, 3, 3, 2, 3, 3, 2, 2, 2, 1]
|
||||||
|
|
||||||
let unique = numbers.uniqued()
|
let unique = numbers.uniqued()
|
||||||
// unique == [1, 2, 3]
|
// Array(unique) == [1, 2, 3]
|
||||||
```
|
```
|
||||||
|
|
||||||
## Detailed Design
|
## Detailed Design
|
||||||
|
|
||||||
Both methods are available for sequences, with the simplest limited to
|
Both methods are available for sequences, with the simplest limited to
|
||||||
when the element type conforms to `Hashable`. Both methods preserve
|
when the element type conforms to `Hashable`. Both methods preserve
|
||||||
the relative order of the elements.
|
the relative order of the elements. `uniqued(on:)` has a matching lazy
|
||||||
|
version that is added to `LazySequenceProtocol`.
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
extension Sequence where Element: Hashable {
|
extension Sequence where Element: Hashable {
|
||||||
func uniqued() -> [Element]
|
func uniqued() -> Uniqued<Self, Element>
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Sequence {
|
extension Sequence {
|
||||||
func uniqued<T>(on: (Element) throws -> T) rethrows -> [Element]
|
func uniqued<Subject>(on projection: (Element) throws -> Subject) rethrows -> [Element]
|
||||||
where T: Hashable
|
where Subject: Hashable
|
||||||
|
}
|
||||||
|
|
||||||
|
extension LazySequenceProtocol {
|
||||||
|
func uniqued<Subject>(on projection: @escaping (Element) -> Subject) -> Uniqued<Self, Subject>
|
||||||
|
where Subject: Hashable
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Complexity
|
### Complexity
|
||||||
|
|
||||||
The `uniqued` methods are O(_n_) in both time and space complexity.
|
The eager `uniqued(on:)` method is O(_n_) in both time and space complexity.
|
||||||
|
The lazy versions are O(_1_).
|
||||||
|
|
||||||
### Comparison with other languages
|
### Comparison with other languages
|
||||||
|
|
||||||
|
|||||||
@@ -25,9 +25,12 @@ Read more about the package, and the intent behind it, in the [announcement on s
|
|||||||
|
|
||||||
#### Subsetting operations
|
#### 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.
|
- [`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.
|
- [`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.
|
- [`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.
|
- [`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
|
#### Partial sorting
|
||||||
@@ -37,12 +40,12 @@ Read more about the package, and the intent behind it, in the [announcement on s
|
|||||||
#### Other useful operations
|
#### 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.
|
- [`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.
|
- [`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.
|
- [`interspersed(with:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Intersperse.md): Place a value between every two elements of a sequence.
|
||||||
- [`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.
|
- [`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.
|
||||||
- [`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.
|
- [`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.
|
||||||
|
- [`windows(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Windows.md): Breaks a collection into overlapping subsequences where elements are slices from the original collection.
|
||||||
|
|
||||||
## Adding Swift Algorithms as a Dependency
|
## Adding Swift Algorithms as a Dependency
|
||||||
|
|
||||||
@@ -59,7 +62,7 @@ If you don't want potentially source-breaking package updates,
|
|||||||
use this dependency specification instead:
|
use this dependency specification instead:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
.package(url: "https://github.com/apple/swift-algorithms", .upToNextMinor(from: "0.0.1")),
|
.package(url: "https://github.com/apple/swift-algorithms", .upToNextMinor(from: "0.1.0")),
|
||||||
```
|
```
|
||||||
|
|
||||||
Finally, include `"Algorithms"` as a dependency for your executable target:
|
Finally, include `"Algorithms"` as a dependency for your executable target:
|
||||||
@@ -68,7 +71,7 @@ Finally, include `"Algorithms"` as a dependency for your executable target:
|
|||||||
let package = Package(
|
let package = Package(
|
||||||
// name, platforms, products, etc.
|
// name, platforms, products, etc.
|
||||||
dependencies: [
|
dependencies: [
|
||||||
.package(url: "https://github.com/apple/swift-algorithms", from: "0.0.1"),
|
.package(url: "https://github.com/apple/swift-algorithms", from: "0.1.0"),
|
||||||
// other dependencies
|
// other dependencies
|
||||||
],
|
],
|
||||||
targets: [
|
targets: [
|
||||||
|
|||||||
@@ -14,10 +14,12 @@ public struct Chain2<Base1: Sequence, Base2: Sequence>
|
|||||||
where Base1.Element == Base2.Element
|
where Base1.Element == Base2.Element
|
||||||
{
|
{
|
||||||
/// The first sequence in this chain.
|
/// The first sequence in this chain.
|
||||||
public let base1: Base1
|
@usableFromInline
|
||||||
|
internal let base1: Base1
|
||||||
|
|
||||||
/// The second sequence in this chain.
|
/// The second sequence in this chain.
|
||||||
public let base2: Base2
|
@usableFromInline
|
||||||
|
internal let base2: Base2
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(base1: Base1, base2: Base2) {
|
internal init(base1: Base1, base2: Base2) {
|
||||||
@@ -100,7 +102,7 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
|
|||||||
/// Converts an index of `Base1` to the corresponding `Index` by mapping
|
/// Converts an index of `Base1` to the corresponding `Index` by mapping
|
||||||
/// `base1.endIndex` to `base2.startIndex`.
|
/// `base1.endIndex` to `base2.startIndex`.
|
||||||
@inlinable
|
@inlinable
|
||||||
internal func convertIndex(_ i: Base1.Index) -> Index {
|
internal func normalizeIndex(_ i: Base1.Index) -> Index {
|
||||||
i == base1.endIndex ? Index(second: base2.startIndex) : Index(first: i)
|
i == base1.endIndex ? Index(second: base2.startIndex) : Index(first: i)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -108,7 +110,7 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
|
|||||||
public var startIndex: Index {
|
public var startIndex: Index {
|
||||||
// if `base1` is empty, this will return `base2.startIndex` - if `base2` is
|
// if `base1` is empty, this will return `base2.startIndex` - if `base2` is
|
||||||
// also empty, this will correctly equal `base2.endIndex`
|
// also empty, this will correctly equal `base2.endIndex`
|
||||||
convertIndex(base1.startIndex)
|
normalizeIndex(base1.startIndex)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
@@ -131,109 +133,116 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
|
|||||||
switch i.position {
|
switch i.position {
|
||||||
case let .first(i):
|
case let .first(i):
|
||||||
assert(i != base1.endIndex)
|
assert(i != base1.endIndex)
|
||||||
return convertIndex(base1.index(after: i))
|
return normalizeIndex(base1.index(after: i))
|
||||||
case let .second(i):
|
case let .second(i):
|
||||||
return Index(second: base2.index(after: i))
|
return Index(second: base2.index(after: i))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(_ i: Index, offsetBy n: Int) -> Index {
|
public func index(_ i: Index, offsetBy distance: Int) -> Index {
|
||||||
if n == 0 { return i }
|
guard distance != 0 else { return i }
|
||||||
return n > 0
|
|
||||||
? offsetForward(i, by: n, limitedBy: endIndex)!
|
return distance > 0
|
||||||
: offsetBackward(i, by: -n, limitedBy: startIndex)!
|
? offsetForward(i, by: distance)
|
||||||
|
: offsetBackward(i, by: -distance)
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public func index(
|
public func index(
|
||||||
_ i: Index,
|
_ i: Index,
|
||||||
offsetBy n: Int,
|
offsetBy distance: Int,
|
||||||
limitedBy limit: Index
|
limitedBy limit: Index
|
||||||
) -> Index? {
|
) -> Index? {
|
||||||
if n == 0 { return i }
|
if distance >= 0 {
|
||||||
return n > 0
|
return limit >= i
|
||||||
? offsetForward(i, by: n, limitedBy: limit)
|
? offsetForward(i, by: distance, limitedBy: limit)
|
||||||
: offsetBackward(i, by: -n, limitedBy: limit)
|
: offsetForward(i, by: distance)
|
||||||
|
} else {
|
||||||
|
return limit <= i
|
||||||
|
? offsetBackward(i, by: -distance, limitedBy: limit)
|
||||||
|
: offsetBackward(i, by: -distance)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@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
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal func offsetForward(
|
internal func offsetForward(
|
||||||
_ i: Index, by n: Int, limitedBy limit: Index
|
_ i: Index, by distance: Int, limitedBy limit: Index
|
||||||
) -> Index? {
|
) -> Index? {
|
||||||
|
assert(distance >= 0)
|
||||||
|
assert(limit >= i)
|
||||||
|
|
||||||
switch (i.position, limit.position) {
|
switch (i.position, limit.position) {
|
||||||
case let (.first(i), .first(limit)):
|
case let (.first(i), .first(limit)):
|
||||||
if limit >= i {
|
return base1.index(i, offsetBy: distance, limitedBy: limit)
|
||||||
// `limit` is relevant, so `base2` cannot be reached
|
.map(Index.init(first:))
|
||||||
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 convertIndex(j)
|
|
||||||
} else {
|
|
||||||
// the offset overflows the bounds of `base1` by `n - d`
|
|
||||||
let d = base1.distance(from: i, to: base1.endIndex)
|
|
||||||
return Index(second: base2.index(base2.startIndex, offsetBy: n - d))
|
|
||||||
}
|
|
||||||
|
|
||||||
case let (.first(i), .second(limit)):
|
case let (.first(i), .second(limit)):
|
||||||
if let j = base1.index(i, offsetBy: n, limitedBy: base1.endIndex) {
|
if let j = base1.index(i, offsetBy: distance, limitedBy: base1.endIndex) {
|
||||||
// the offset stays within the bounds of `base1`
|
// the offset stays within the bounds of `base1`
|
||||||
return convertIndex(j)
|
return normalizeIndex(j)
|
||||||
} else {
|
} else {
|
||||||
// the offset overflows the bounds of `base1` by `n - d`
|
// the offset overflows the bounds of `base1` by `n - d`
|
||||||
let d = base1.distance(from: i, to: base1.endIndex)
|
let d = base1.distance(from: i, to: base1.endIndex)
|
||||||
return base2.index(base2.startIndex, offsetBy: n - d, limitedBy: limit)
|
return base2.index(base2.startIndex, offsetBy: distance - d, limitedBy: limit)
|
||||||
.map(Index.init(second:))
|
.map(Index.init(second:))
|
||||||
}
|
}
|
||||||
|
|
||||||
case let (.second(i), .first):
|
case (.second, .first):
|
||||||
// `limit` has no effect here
|
// impossible because `limit >= i`
|
||||||
return Index(second: base2.index(i, offsetBy: n))
|
fatalError()
|
||||||
|
|
||||||
case let (.second(i), .second(limit)):
|
case let (.second(i), .second(limit)):
|
||||||
return base2.index(i, offsetBy: n, limitedBy: limit)
|
return base2.index(i, offsetBy: distance, limitedBy: limit)
|
||||||
.map(Index.init(second:))
|
.map(Index.init(second:))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal func offsetBackward(
|
internal func offsetBackward(
|
||||||
_ i: Index, by n: Int, limitedBy limit: Index
|
_ i: Index, by distance: Int, limitedBy limit: Index
|
||||||
) -> Index? {
|
) -> Index? {
|
||||||
|
assert(distance >= 0)
|
||||||
|
assert(limit <= i)
|
||||||
|
|
||||||
switch (i.position, limit.position) {
|
switch (i.position, limit.position) {
|
||||||
case let (.first(i), .first(limit)):
|
case let (.first(i), .first(limit)):
|
||||||
return base1.index(i, offsetBy: -n, limitedBy: limit)
|
return base1.index(i, offsetBy: -distance, limitedBy: limit)
|
||||||
.map(Index.init(first:))
|
.map(Index.init(first:))
|
||||||
|
|
||||||
case let (.first(i), .second):
|
case (.first, .second):
|
||||||
// `limit` has no effect here
|
// impossible because `limit <= i`
|
||||||
return Index(first: base1.index(i, offsetBy: -n))
|
fatalError()
|
||||||
|
|
||||||
case let (.second(i), .first(limit)):
|
case let (.second(i), .first(limit)):
|
||||||
if let j = base2.index(i, offsetBy: -n, limitedBy: base2.startIndex) {
|
if let j = base2.index(i, offsetBy: -distance, limitedBy: base2.startIndex) {
|
||||||
// the offset stays within the bounds of `base2`
|
// the offset stays within the bounds of `base2`
|
||||||
return Index(second: j)
|
return Index(second: j)
|
||||||
} else {
|
} else {
|
||||||
// the offset overflows the bounds of `base2` by `n - d`
|
// the offset overflows the bounds of `base2` by `n - d`
|
||||||
let d = base2.distance(from: base2.startIndex, to: i)
|
let d = base2.distance(from: base2.startIndex, to: i)
|
||||||
return base1.index(base1.endIndex, offsetBy: -(n - d), limitedBy: limit)
|
return base1.index(base1.endIndex, offsetBy: -(distance - d), limitedBy: limit)
|
||||||
.map(Index.init(first:))
|
.map(Index.init(first:))
|
||||||
}
|
}
|
||||||
|
|
||||||
case let (.second(i), .second(limit)):
|
case let (.second(i), .second(limit)):
|
||||||
if limit <= i {
|
// `limit` is relevant, so `base1` cannot be reached
|
||||||
// `limit` is relevant, so `base1` cannot be reached
|
return base2.index(i, offsetBy: -distance, limitedBy: limit)
|
||||||
return base2.index(i, offsetBy: -n, limitedBy: limit)
|
.map(Index.init(second:))
|
||||||
.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)))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -274,9 +283,6 @@ extension Chain2: BidirectionalCollection
|
|||||||
extension Chain2: RandomAccessCollection
|
extension Chain2: RandomAccessCollection
|
||||||
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
|
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
|
||||||
|
|
||||||
extension Chain2: Equatable where Base1: Equatable, Base2: Equatable {}
|
|
||||||
extension Chain2: Hashable where Base1: Hashable, Base2: Hashable {}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
// chain(_:_:)
|
// chain(_:_:)
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|||||||
@@ -11,9 +11,10 @@
|
|||||||
|
|
||||||
/// A collection wrapper that breaks a collection into chunks based on a
|
/// A collection wrapper that breaks a collection into chunks based on a
|
||||||
/// predicate or projection.
|
/// predicate or projection.
|
||||||
public struct LazyChunked<Base: Collection, Subject> {
|
public struct Chunked<Base: Collection, Subject> {
|
||||||
/// The collection that this instance provides a view onto.
|
/// The collection that this instance provides a view onto.
|
||||||
public let base: Base
|
@usableFromInline
|
||||||
|
internal let base: Base
|
||||||
|
|
||||||
/// The projection function.
|
/// The projection function.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
@@ -44,7 +45,7 @@ public struct LazyChunked<Base: Collection, Subject> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension LazyChunked: LazyCollectionProtocol {
|
extension Chunked: LazyCollectionProtocol {
|
||||||
/// A position in a chunked collection.
|
/// A position in a chunked collection.
|
||||||
public struct Index: Comparable {
|
public struct Index: Comparable {
|
||||||
/// The range corresponding to the chunk at this position.
|
/// The range corresponding to the chunk at this position.
|
||||||
@@ -105,9 +106,9 @@ extension LazyChunked: LazyCollectionProtocol {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension LazyChunked.Index: Hashable where Base.Index: Hashable {}
|
extension Chunked.Index: Hashable where Base.Index: Hashable {}
|
||||||
|
|
||||||
extension LazyChunked: BidirectionalCollection
|
extension Chunked: BidirectionalCollection
|
||||||
where Base: BidirectionalCollection
|
where Base: BidirectionalCollection
|
||||||
{
|
{
|
||||||
/// Returns the index in the base collection of the start of the chunk ending
|
/// Returns the index in the base collection of the start of the chunk ending
|
||||||
@@ -130,6 +131,9 @@ extension LazyChunked: BidirectionalCollection
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@available(*, deprecated, renamed: "Chunked")
|
||||||
|
public typealias LazyChunked<Base: Collection, Subject> = Chunked<Base, Subject>
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
// lazy.chunked(by:)
|
// lazy.chunked(by:)
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
@@ -142,8 +146,8 @@ extension LazyCollectionProtocol {
|
|||||||
@inlinable
|
@inlinable
|
||||||
public func chunked(
|
public func chunked(
|
||||||
by belongInSameGroup: @escaping (Element, Element) -> Bool
|
by belongInSameGroup: @escaping (Element, Element) -> Bool
|
||||||
) -> LazyChunked<Elements, Element> {
|
) -> Chunked<Elements, Element> {
|
||||||
LazyChunked(
|
Chunked(
|
||||||
base: elements,
|
base: elements,
|
||||||
projection: { $0 },
|
projection: { $0 },
|
||||||
belongInSameGroup: belongInSameGroup)
|
belongInSameGroup: belongInSameGroup)
|
||||||
@@ -156,8 +160,8 @@ extension LazyCollectionProtocol {
|
|||||||
@inlinable
|
@inlinable
|
||||||
public func chunked<Subject: Equatable>(
|
public func chunked<Subject: Equatable>(
|
||||||
on projection: @escaping (Element) -> Subject
|
on projection: @escaping (Element) -> Subject
|
||||||
) -> LazyChunked<Elements, Subject> {
|
) -> Chunked<Elements, Subject> {
|
||||||
LazyChunked(
|
Chunked(
|
||||||
base: elements,
|
base: elements,
|
||||||
projection: projection,
|
projection: projection,
|
||||||
belongInSameGroup: ==)
|
belongInSameGroup: ==)
|
||||||
@@ -508,20 +512,6 @@ 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 {}
|
extension ChunkedByCount.Index: Hashable where Base.Index: Hashable {}
|
||||||
|
|
||||||
// Lazy conditional conformance.
|
// Lazy conditional conformance.
|
||||||
|
|||||||
@@ -12,7 +12,8 @@
|
|||||||
/// A collection wrapper that generates combinations of a base collection.
|
/// A collection wrapper that generates combinations of a base collection.
|
||||||
public struct Combinations<Base: Collection> {
|
public struct Combinations<Base: Collection> {
|
||||||
/// The collection to iterate over for combinations.
|
/// The collection to iterate over for combinations.
|
||||||
public let base: Base
|
@usableFromInline
|
||||||
|
internal let base: Base
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let baseCount: Int
|
internal let baseCount: Int
|
||||||
@@ -180,8 +181,6 @@ extension Combinations: Sequence {
|
|||||||
}
|
}
|
||||||
|
|
||||||
extension Combinations: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
extension Combinations: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||||
extension Combinations: Equatable where Base: Equatable {}
|
|
||||||
extension Combinations: Hashable where Base: Hashable {}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
// combinations(ofCount:)
|
// combinations(ofCount:)
|
||||||
|
|||||||
@@ -0,0 +1,181 @@
|
|||||||
|
//===----------------------------------------------------------------------===//
|
||||||
|
//
|
||||||
|
// 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 {}
|
||||||
@@ -12,7 +12,8 @@
|
|||||||
/// A collection wrapper that repeats the elements of a base collection.
|
/// A collection wrapper that repeats the elements of a base collection.
|
||||||
public struct Cycle<Base: Collection> {
|
public struct Cycle<Base: Collection> {
|
||||||
/// The collection to repeat.
|
/// The collection to repeat.
|
||||||
public let base: Base
|
@usableFromInline
|
||||||
|
internal let base: Base
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(base: Base) {
|
internal init(base: Base) {
|
||||||
@@ -24,10 +25,10 @@ extension Cycle: Sequence {
|
|||||||
/// The iterator for a `Cycle` sequence.
|
/// The iterator for a `Cycle` sequence.
|
||||||
public struct Iterator: IteratorProtocol {
|
public struct Iterator: IteratorProtocol {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
let base: Base
|
internal let base: Base
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
var current: Base.Index
|
internal var current: Base.Index
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(base: Base) {
|
internal init(base: Base) {
|
||||||
@@ -56,6 +57,112 @@ extension Cycle: Sequence {
|
|||||||
|
|
||||||
extension Cycle: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
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()
|
// cycled()
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
@@ -109,7 +216,7 @@ extension Collection {
|
|||||||
///
|
///
|
||||||
/// - Complexity: O(1)
|
/// - Complexity: O(1)
|
||||||
@inlinable
|
@inlinable
|
||||||
public func cycled(times: Int) -> FlattenSequence<Repeated<Self>> {
|
public func cycled(times: Int) -> FiniteCycle<Self> {
|
||||||
repeatElement(self, count: times).joined()
|
FiniteCycle(base: self, times: times)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -14,15 +14,30 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
public extension Sequence {
|
public extension Sequence {
|
||||||
/// Returns the first element in `self` that `transform` maps to a `.some`.
|
/// 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.
|
||||||
func firstNonNil<Result>(
|
func firstNonNil<Result>(
|
||||||
_ transform: (Element) throws -> Result?
|
_ transform: (Element) throws -> Result?
|
||||||
) rethrows -> Result? {
|
) rethrows -> Result? {
|
||||||
for value in self {
|
for value in self {
|
||||||
if let value = try transform(value) {
|
if let value = try transform(value) {
|
||||||
return value
|
return value
|
||||||
}
|
}
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -16,7 +16,8 @@ public struct Indexed<Base: Collection> {
|
|||||||
public typealias Element = (index: Base.Index, element: Base.Element)
|
public typealias Element = (index: Base.Index, element: Base.Element)
|
||||||
|
|
||||||
/// The base collection.
|
/// The base collection.
|
||||||
public let base: Base
|
@usableFromInline
|
||||||
|
internal let base: Base
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(base: Base) {
|
internal init(base: Base) {
|
||||||
@@ -71,8 +72,6 @@ extension Indexed: BidirectionalCollection where Base: BidirectionalCollection {
|
|||||||
extension Indexed: RandomAccessCollection where Base: RandomAccessCollection {}
|
extension Indexed: RandomAccessCollection where Base: RandomAccessCollection {}
|
||||||
extension Indexed: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
extension Indexed: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||||
extension Indexed: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
|
extension Indexed: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
|
||||||
extension Indexed: Equatable where Base: Equatable {}
|
|
||||||
extension Indexed: Hashable where Base: Hashable {}
|
|
||||||
|
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
// indexed()
|
// indexed()
|
||||||
|
|||||||
@@ -78,7 +78,8 @@ extension MutableCollection
|
|||||||
/// A sequence of all the permutations of a collection's elements.
|
/// A sequence of all the permutations of a collection's elements.
|
||||||
public struct Permutations<Base: Collection> {
|
public struct Permutations<Base: Collection> {
|
||||||
/// The base collection to iterate over for permutations.
|
/// The base collection to iterate over for permutations.
|
||||||
public let base: Base
|
@usableFromInline
|
||||||
|
internal let base: Base
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let baseCount: Int
|
internal let baseCount: Int
|
||||||
@@ -137,7 +138,7 @@ extension Permutations: Sequence {
|
|||||||
/// The iterator for a `Permutations` instance.
|
/// The iterator for a `Permutations` instance.
|
||||||
public struct Iterator: IteratorProtocol {
|
public struct Iterator: IteratorProtocol {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var base: Base
|
internal let base: Base
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal let baseCount: Int
|
internal let baseCount: Int
|
||||||
@@ -397,7 +398,8 @@ extension Collection {
|
|||||||
/// `uniquePermutations` methods on your collection.
|
/// `uniquePermutations` methods on your collection.
|
||||||
public struct UniquePermutations<Base: Collection> {
|
public struct UniquePermutations<Base: Collection> {
|
||||||
/// The base collection to iterate over for permutations.
|
/// The base collection to iterate over for permutations.
|
||||||
public let base: Base
|
@usableFromInline
|
||||||
|
internal let base: Base
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var indexes: [Base.Index]
|
internal var indexes: [Base.Index]
|
||||||
|
|||||||
@@ -12,9 +12,12 @@
|
|||||||
/// A sequence that represents the product of two sequences' elements.
|
/// A sequence that represents the product of two sequences' elements.
|
||||||
public struct Product2<Base1: Sequence, Base2: Collection> {
|
public struct Product2<Base1: Sequence, Base2: Collection> {
|
||||||
/// The outer sequence in the product.
|
/// The outer sequence in the product.
|
||||||
public let base1: Base1
|
@usableFromInline
|
||||||
|
internal let base1: Base1
|
||||||
|
|
||||||
/// The inner sequence in the product.
|
/// The inner sequence in the product.
|
||||||
public let base2: Base2
|
@usableFromInline
|
||||||
|
internal let base2: Base2
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
internal init(_ base1: Base1, _ base2: Base2) {
|
internal init(_ base1: Base1, _ base2: Base2) {
|
||||||
@@ -44,7 +47,8 @@ extension Product2: Sequence {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@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
|
// This is the initial state, where i1.next() has never
|
||||||
// been called, or the final state, where i1.next() has
|
// been called, or the final state, where i1.next() has
|
||||||
// already returned nil.
|
// already returned nil.
|
||||||
@@ -121,7 +125,8 @@ extension Product2: Collection where Base1: Collection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
public subscript(position: Index) -> (Base1.Element, Base2.Element) {
|
public subscript(position: Index) -> (Base1.Element,
|
||||||
|
Base2.Element) {
|
||||||
(base1[position.i1], base2[position.i2])
|
(base1[position.i1], base2[position.i2])
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -433,8 +438,6 @@ extension Product2: RandomAccessCollection
|
|||||||
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
|
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
|
||||||
|
|
||||||
extension Product2.Index: Hashable where Base1.Index: Hashable, Base2.Index: Hashable {}
|
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(_:_:)
|
// product(_:_:)
|
||||||
|
|||||||
@@ -39,9 +39,7 @@ extension LazySequenceProtocol {
|
|||||||
_ initial: Result,
|
_ initial: Result,
|
||||||
_ transform: @escaping (Result, Element) -> Result
|
_ transform: @escaping (Result, Element) -> Result
|
||||||
) -> ExclusiveReductions<Result, Self> {
|
) -> ExclusiveReductions<Result, Self> {
|
||||||
|
return reductions(into: initial) { result, element in
|
||||||
var result = initial
|
|
||||||
return reductions(into: &result) { result, element in
|
|
||||||
result = transform(result, element)
|
result = transform(result, element)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -69,7 +67,7 @@ extension LazySequenceProtocol {
|
|||||||
/// - Complexity: O(1)
|
/// - Complexity: O(1)
|
||||||
@inlinable
|
@inlinable
|
||||||
public func reductions<Result>(
|
public func reductions<Result>(
|
||||||
into initial: inout Result,
|
into initial: Result,
|
||||||
_ transform: @escaping (inout Result, Element) -> Void
|
_ transform: @escaping (inout Result, Element) -> Void
|
||||||
) -> ExclusiveReductions<Result, Self> {
|
) -> ExclusiveReductions<Result, Self> {
|
||||||
ExclusiveReductions(base: self, initial: initial, transform: transform)
|
ExclusiveReductions(base: self, initial: initial, transform: transform)
|
||||||
@@ -117,9 +115,7 @@ extension Sequence {
|
|||||||
_ initial: Result,
|
_ initial: Result,
|
||||||
_ transform: (Result, Element) throws -> Result
|
_ transform: (Result, Element) throws -> Result
|
||||||
) rethrows -> [Result] {
|
) rethrows -> [Result] {
|
||||||
|
return try reductions(into: initial) { result, element in
|
||||||
var result = initial
|
|
||||||
return try reductions(into: &result) { result, element in
|
|
||||||
result = try transform(result, element)
|
result = try transform(result, element)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -160,7 +156,7 @@ extension Sequence {
|
|||||||
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
|
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
|
||||||
@inlinable
|
@inlinable
|
||||||
public func reductions<Result>(
|
public func reductions<Result>(
|
||||||
into initial: inout Result,
|
into initial: Result,
|
||||||
_ transform: (inout Result, Element) throws -> Void
|
_ transform: (inout Result, Element) throws -> Void
|
||||||
) rethrows -> [Result] {
|
) rethrows -> [Result] {
|
||||||
|
|
||||||
@@ -168,6 +164,7 @@ extension Sequence {
|
|||||||
output.reserveCapacity(underestimatedCount + 1)
|
output.reserveCapacity(underestimatedCount + 1)
|
||||||
output.append(initial)
|
output.append(initial)
|
||||||
|
|
||||||
|
var initial = initial
|
||||||
for element in self {
|
for element in self {
|
||||||
try transform(&initial, element)
|
try transform(&initial, element)
|
||||||
output.append(initial)
|
output.append(initial)
|
||||||
@@ -595,10 +592,10 @@ extension LazySequenceProtocol {
|
|||||||
@available(*, deprecated, message: "Use reductions(into:_:) instead.")
|
@available(*, deprecated, message: "Use reductions(into:_:) instead.")
|
||||||
@inlinable
|
@inlinable
|
||||||
public func scan<Result>(
|
public func scan<Result>(
|
||||||
into initial: inout Result,
|
into initial: Result,
|
||||||
_ transform: @escaping (inout Result, Element) -> Void
|
_ transform: @escaping (inout Result, Element) -> Void
|
||||||
) -> ExclusiveReductions<Result, Self> {
|
) -> ExclusiveReductions<Result, Self> {
|
||||||
reductions(into: &initial, transform)
|
reductions(into: initial, transform)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -616,10 +613,10 @@ extension Sequence {
|
|||||||
@available(*, deprecated, message: "Use reductions(into:_:) instead.")
|
@available(*, deprecated, message: "Use reductions(into:_:) instead.")
|
||||||
@inlinable
|
@inlinable
|
||||||
public func scan<Result>(
|
public func scan<Result>(
|
||||||
into initial: inout Result,
|
into initial: Result,
|
||||||
_ transform: (inout Result, Element) throws -> Void
|
_ transform: (inout Result, Element) throws -> Void
|
||||||
) rethrows -> [Result] {
|
) rethrows -> [Result] {
|
||||||
try reductions(into: &initial, transform)
|
try reductions(into: initial, transform)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -269,22 +269,4 @@ extension StrideCollection: BidirectionalCollection
|
|||||||
}
|
}
|
||||||
|
|
||||||
extension StrideCollection: RandomAccessCollection where Base: RandomAccessCollection {}
|
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 {}
|
extension StrideCollection.Index: Hashable where Base.Index: Hashable {}
|
||||||
@@ -9,25 +9,82 @@
|
|||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
|
/// 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()
|
// uniqued()
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
extension Sequence where Element: Hashable {
|
extension Sequence where Element: Hashable {
|
||||||
/// Returns an array with only the unique elements of this sequence, in the
|
/// Returns a sequence with only the unique elements of this sequence, in the
|
||||||
/// order of the first occurrence of each unique element.
|
/// order of the first occurrence of each unique element.
|
||||||
///
|
///
|
||||||
/// let animals = ["dog", "pig", "cat", "ox", "dog", "cat"]
|
/// let animals = ["dog", "pig", "cat", "ox", "dog", "cat"]
|
||||||
/// let uniqued = animals.uniqued()
|
/// let uniqued = animals.uniqued()
|
||||||
/// print(uniqued)
|
/// print(Array(uniqued))
|
||||||
/// // Prints '["dog", "pig", "cat", "ox"]'
|
/// // Prints '["dog", "pig", "cat", "ox"]'
|
||||||
///
|
///
|
||||||
/// - Returns: An array with only the unique elements of this sequence.
|
/// - Returns: A sequence with only the unique elements of this sequence.
|
||||||
/// .
|
/// .
|
||||||
/// - Complexity: O(*n*), where *n* is the length of the sequence.
|
/// - Complexity: O(1).
|
||||||
@inlinable
|
@inlinable
|
||||||
public func uniqued() -> [Element] {
|
public func uniqued() -> Uniqued<Self, Element> {
|
||||||
uniqued(on: { $0 })
|
Uniqued(base: self, projection: { $0 })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -40,7 +97,7 @@ extension Sequence {
|
|||||||
/// first characters:
|
/// first characters:
|
||||||
///
|
///
|
||||||
/// let animals = ["dog", "pig", "cat", "ox", "cow", "owl"]
|
/// let animals = ["dog", "pig", "cat", "ox", "cow", "owl"]
|
||||||
/// let uniqued = animals.uniqued(on: {$0.first})
|
/// let uniqued = animals.uniqued(on: { $0.first })
|
||||||
/// print(uniqued)
|
/// print(uniqued)
|
||||||
/// // Prints '["dog", "pig", "cat", "ox"]'
|
/// // Prints '["dog", "pig", "cat", "ox"]'
|
||||||
///
|
///
|
||||||
@@ -67,3 +124,21 @@ extension Sequence {
|
|||||||
return result
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -47,8 +47,11 @@ extension Collection {
|
|||||||
/// A collection wrapper that presents a sliding window over the elements of
|
/// A collection wrapper that presents a sliding window over the elements of
|
||||||
/// a collection.
|
/// a collection.
|
||||||
public struct Windows<Base: Collection> {
|
public struct Windows<Base: Collection> {
|
||||||
public let base: Base
|
@usableFromInline
|
||||||
public let size: Int
|
internal let base: Base
|
||||||
|
|
||||||
|
@usableFromInline
|
||||||
|
internal let size: Int
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
internal var firstUpperBound: Base.Index?
|
internal var firstUpperBound: Base.Index?
|
||||||
@@ -347,6 +350,4 @@ extension Windows: BidirectionalCollection where Base: BidirectionalCollection {
|
|||||||
extension Windows: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
extension Windows: LazySequenceProtocol where Base: LazySequenceProtocol {}
|
||||||
extension Windows: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
|
extension Windows: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
|
||||||
extension Windows: RandomAccessCollection where Base: RandomAccessCollection {}
|
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 {}
|
extension Windows.Index: Hashable where Base.Index: Hashable {}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
//===----------------------------------------------------------------------===//
|
||||||
|
//
|
||||||
|
// 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())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,28 +19,70 @@ final class CycleTests: XCTestCase {
|
|||||||
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],
|
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],
|
||||||
cycle.prefix(20)
|
cycle.prefix(20)
|
||||||
)
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testCycleClosedRangePrefix() {
|
||||||
let a = Array((0..<17).cycled().prefix(10_000))
|
let a = Array((0..<17).cycled().prefix(10_000))
|
||||||
XCTAssertEqual(10_000, a.count)
|
XCTAssertEqual(10_000, a.count)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testEmptyCycle() {
|
||||||
let empty = Array("".cycled())
|
let empty = Array("".cycled())
|
||||||
XCTAssert(empty.isEmpty)
|
XCTAssert(empty.isEmpty)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func testCycleLazy() {
|
||||||
|
XCTAssertLazySequence((1...4).lazy.cycled())
|
||||||
|
}
|
||||||
|
|
||||||
func testRepeated() {
|
func testRepeated() {
|
||||||
let repeats = (1...4).cycled(times: 3)
|
let repeats = (1...4).cycled(times: 3)
|
||||||
XCTAssertEqualSequences(
|
XCTAssertEqualSequences(
|
||||||
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],
|
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],
|
||||||
repeats)
|
repeats)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testRepeatedClosedRange() {
|
||||||
|
let repeats = Array((1..<5).cycled(times: 2500))
|
||||||
|
XCTAssertEqual(10_000, repeats.count)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testRepeatedEmptyCollection() {
|
||||||
let empty1 = Array("".cycled(times: 100))
|
let empty1 = Array("".cycled(times: 100))
|
||||||
XCTAssert(empty1.isEmpty)
|
XCTAssert(empty1.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testRepeatedZeroTimesCycle() {
|
||||||
let empty2 = Array("Hello".cycled(times: 0))
|
let empty2 = Array("Hello".cycled(times: 0))
|
||||||
XCTAssert(empty2.isEmpty)
|
XCTAssert(empty2.isEmpty)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testCycleLazy() {
|
func testRepeatedLazy() {
|
||||||
XCTAssertLazySequence((1...4).lazy.cycled())
|
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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -27,17 +27,11 @@ final class ReductionsTests: XCTestCase {
|
|||||||
XCTAssertEqualCollections([1].lazy.reductions(0, +), [0, 1])
|
XCTAssertEqualCollections([1].lazy.reductions(0, +), [0, 1])
|
||||||
XCTAssertEqualCollections(EmptyCollection<Int>().lazy.reductions(0, +), [0])
|
XCTAssertEqualCollections(EmptyCollection<Int>().lazy.reductions(0, +), [0])
|
||||||
|
|
||||||
var value = 0
|
XCTAssertEqual([1, 2, 3, 4].lazy.reductions(into: 0, +=), [0, 1, 3, 6, 10])
|
||||||
XCTAssertEqual([1, 2, 3, 4].lazy.reductions(into: &value, +=), [0, 1, 3, 6, 10])
|
|
||||||
XCTAssertEqual(value, 10)
|
|
||||||
|
|
||||||
value = 0
|
XCTAssertEqual([1].lazy.reductions(into: 0, +=), [0, 1])
|
||||||
XCTAssertEqual([1].lazy.reductions(into: &value, +=), [0, 1])
|
|
||||||
XCTAssertEqual(value, 1)
|
|
||||||
|
|
||||||
value = 0
|
XCTAssertEqual(EmptyCollection<Int>().lazy.reductions(into: 0, +=), [0])
|
||||||
XCTAssertEqual(EmptyCollection<Int>().lazy.reductions(into: &value, +=), [0])
|
|
||||||
XCTAssertEqual(value, 0)
|
|
||||||
|
|
||||||
XCTAssertLazySequence((1...).prefix(1).lazy.reductions(0, +))
|
XCTAssertLazySequence((1...).prefix(1).lazy.reductions(0, +))
|
||||||
XCTAssertLazySequence([1].lazy.reductions(0, +))
|
XCTAssertLazySequence([1].lazy.reductions(0, +))
|
||||||
@@ -49,17 +43,11 @@ final class ReductionsTests: XCTestCase {
|
|||||||
XCTAssertEqual([1].reductions(0, +), [0, 1])
|
XCTAssertEqual([1].reductions(0, +), [0, 1])
|
||||||
XCTAssertEqual(EmptyCollection<Int>().reductions(0, +), [0])
|
XCTAssertEqual(EmptyCollection<Int>().reductions(0, +), [0])
|
||||||
|
|
||||||
var value = 0
|
XCTAssertEqual([1, 2, 3, 4].reductions(into: 0, +=), [0, 1, 3, 6, 10])
|
||||||
XCTAssertEqual([1, 2, 3, 4].reductions(into: &value, +=), [0, 1, 3, 6, 10])
|
|
||||||
XCTAssertEqual(value, 10)
|
|
||||||
|
|
||||||
value = 0
|
XCTAssertEqual([1].reductions(into: 0, +=), [0, 1])
|
||||||
XCTAssertEqual([1].reductions(into: &value, +=), [0, 1])
|
|
||||||
XCTAssertEqual(value, 1)
|
|
||||||
|
|
||||||
value = 0
|
XCTAssertEqual(EmptyCollection<Int>().reductions(into: 0, +=), [0])
|
||||||
XCTAssertEqual(EmptyCollection<Int>().reductions(into: &value, +=), [0])
|
|
||||||
XCTAssertEqual(value, 0)
|
|
||||||
|
|
||||||
XCTAssertNoThrow(try [].reductions(0) { _, _ in throw TestError() })
|
XCTAssertNoThrow(try [].reductions(0) { _, _ in throw TestError() })
|
||||||
XCTAssertThrowsError(try [1].reductions(0) { _, _ in throw TestError() })
|
XCTAssertThrowsError(try [1].reductions(0) { _, _ in throw TestError() })
|
||||||
|
|||||||
@@ -64,19 +64,6 @@ final class StridingTests: XCTestCase {
|
|||||||
// a.index(after: a.endIndex) // Precondition failed: Advancing past end index
|
// 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() {
|
func testStrideLast() {
|
||||||
XCTAssertEqual((1...10).striding(by: 2).last, 9) // 1, 3, 5, 7, 9
|
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
|
XCTAssertEqual((1...10).striding(by: 3).last, 10) // 1, 4, 7, 10
|
||||||
|
|||||||
@@ -17,10 +17,13 @@ final class UniqueTests: XCTestCase {
|
|||||||
let a = repeatElement(1...10, count: 15).joined().shuffled()
|
let a = repeatElement(1...10, count: 15).joined().shuffled()
|
||||||
let b = a.uniqued()
|
let b = a.uniqued()
|
||||||
XCTAssertEqual(b.sorted(), Set(a).sorted())
|
XCTAssertEqual(b.sorted(), Set(a).sorted())
|
||||||
XCTAssertEqual(10, b.count)
|
XCTAssertEqual(10, Array(b).count)
|
||||||
|
|
||||||
let c: [Int] = []
|
let c: [Int] = []
|
||||||
XCTAssertEqual(c.uniqued(), [])
|
XCTAssertEqualSequences(c.uniqued(), [])
|
||||||
|
|
||||||
|
let d = Array(repeating: 1, count: 10)
|
||||||
|
XCTAssertEqualSequences(d.uniqued(), [1])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testUniqueOn() {
|
func testUniqueOn() {
|
||||||
@@ -30,5 +33,21 @@ final class UniqueTests: XCTestCase {
|
|||||||
|
|
||||||
let c: [Int] = []
|
let c: [Int] = []
|
||||||
XCTAssertEqual(c.uniqued(on: { $0.bitWidth }), [])
|
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"])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user