mirror of
https://github.com/apple/swift-algorithms
synced 2026-11-27 04:34:21 +00:00
Compare commits
3
Commits
reductions-into
...
0.0.4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4cca4895cc | ||
|
|
001247f8a5 | ||
|
|
0065c60a22 |
No files matched your search
+37
-1
@@ -16,6 +16,33 @@ package updates, you can specify your package dependency using
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## [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 +123,8 @@ 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.0.4...HEAD
|
||||||
|
[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,20 +135,26 @@ 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
|
||||||
[#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
|
||||||
|
[#91]: https://github.com/apple/swift-algorithms/pull/91
|
||||||
|
|
||||||
<!-- 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
|
||||||
@@ -133,6 +167,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 +175,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
|
||||||
+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.
|
||||||
@@ -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]
|
||||||
|
|
||||||
|
|||||||
@@ -27,7 +27,9 @@ Read more about the package, and the intent behind it, in the [announcement on s
|
|||||||
|
|
||||||
- [`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 +39,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
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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() })
|
||||||
|
|||||||
Reference in new issue
Block a user