Compare commits

...
3 Commits
Author SHA1 Message Date
Nate Cook 4cca4895cc Update changelog for 0.0.4 release (#120) 2021-03-29 14:25:46 -05:00
Tim Vermeulen 001247f8a5 Expand the firstNonNil(_:) docs (#115)
* Fix indentation

* Improve documentation
2021-03-29 19:18:56 +02:00
Kyle Macomber 0065c60a22 Remove the inout on reductions(into:_:) to be consistent with the stdlib reduce(into:_) (#118) 2021-03-27 07:17:34 -07:00
7 changed files with 143 additions and 68 deletions

No files matched your search

+37 -1
View File
@@ -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
### Additions
@@ -96,7 +123,8 @@ This changelog's format is based on [Keep a Changelog](https://keepachangelog.co
<!-- Link references for releases -->
[Unreleased]: https://github.com/apple/swift-algorithms/compare/0.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.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
@@ -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
[#20]: https://github.com/apple/swift-algorithms/pull/20
[#24]: https://github.com/apple/swift-algorithms/pull/24
[#31]: https://github.com/apple/swift-algorithms/pull/31
[#35]: https://github.com/apple/swift-algorithms/pull/35
[#46]: https://github.com/apple/swift-algorithms/pull/46
[#51]: https://github.com/apple/swift-algorithms/pull/51
[#54]: https://github.com/apple/swift-algorithms/pull/54
[#56]: https://github.com/apple/swift-algorithms/pull/56
[#65]: https://github.com/apple/swift-algorithms/pull/65
[#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 -->
[AustinConlon]: https://github.com/apple/swift-algorithms/commits?author=AustinConlon
[benrimmington]: https://github.com/apple/swift-algorithms/commits?author=benrimmington
[bjhomer]: https://github.com/apple/swift-algorithms/commits?author=bjhomer
[danielctull]: https://github.com/apple/swift-algorithms/commits?author=danielctull
[dhruvshah8]: https://github.com/apple/swift-algorithms/commits?author=dhruvshah8
[egorzhdan]: https://github.com/apple/swift-algorithms/commits?author=egorzhdan
[hashemi]: https://github.com/apple/swift-algorithms/commits?author=hashemi
[IanKeen]: https://github.com/apple/swift-algorithms/commits?author=IanKeen
[iSame7]: https://github.com/apple/swift-algorithms/commits?author=iSame7
[karwa]: https://github.com/apple/swift-algorithms/commits?author=karwa
@@ -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
[ollieatkinson]: https://github.com/apple/swift-algorithms/commits?author=ollieatkinson
[pmtao]: https://github.com/apple/swift-algorithms/commits?author=pmtao
[Qata]: https://github.com/apple/swift-algorithms/commits?author=Qata
[rakaramos]: https://github.com/apple/swift-algorithms/commits?author=rakaramos
[rockbruno]: https://github.com/apple/swift-algorithms/commits?author=rockbruno
[Roshankumar350]: https://github.com/apple/swift-algorithms/commits?author=Roshankumar350
@@ -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
[stephentyrone]: https://github.com/apple/swift-algorithms/commits?author=stephentyrone
[timvermeulen]: https://github.com/apple/swift-algorithms/commits?author=timvermeulen
[toddthomas]: https://github.com/apple/swift-algorithms/commits?author=toddthomas
+60 -18
View File
@@ -2,23 +2,48 @@
[[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)]
Retrieves the first `.some` encountered while applying the given transform.
This operation is available through the `firstNonNil(_:)` method on any sequence.
Returns the first non-`nil` result obtained from applying the given
transformation to the elements of the sequence.
```swift
let value = ["A", "B", "10"].firstNonNil { Int($0) }
// value == .some(10)
//
let noValue = ["A", "B", "C"].firstNonNil { Int($0) }
// noValue == .none
let strings = ["three", "3.14", "-5", "2"]
if let firstInt = strings.firstNonNil({ Int($0) }) {
print(firstInt)
// -5
}
```
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
a `.some` is found, unlike using lazy operators, which will load any sequence into a collection
before evaluating its transforms lazily.
```swift
let strings = ["three", "3.14", "-5", "2"]
if let firstIntAsString = strings.first(where: { Int($0) != nil }) {
let firstInt = Int(firstIntAsString)! // :(
// ...
}
```
This method's behavior can also be approximated using `compactMap(_:)`:
```swift
let strings = ["three", "3.14", "-5", "2"]
if let firstInt = strings.compactMap({ Int($0) }).first {
// ...
}
```
However, unlike `firstNonNil(_:)` and `first(where:)`, `compactMap(_:)` does not
stop iterating the sequence once the first match is found. Adding `.lazy` fixes
this, at the cost of requiring an escaping closure that you cannot `throw` from:
```swift
let strings = ["three", "3.14", "-5", "2"]
if let firstInt = strings.lazy.compactMap({ Int($0) }).first {
// ...
}
```
## Detailed Design
@@ -27,17 +52,34 @@ protocol:
```swift
public extension Sequence {
func firstNonNil<Result>(_ transform: (Element) throws -> Result?)
rethrows -> Result?
func firstNonNil<Result>(
_ transform: (Element) throws -> Result?
) rethrows -> Result?
}
```
### Complexity
`firstNonNil(_:)` is an O(*n*) operation, where *n* is the number of
elements at the start of the sequence that result in `nil` when applying the
transformation.
### Naming
This method’s name was selected for its comprehensibility.
Some alternative names were considered:
* `compactMapFirst(_:)`
* `first(mapping:)`
* `firstSome(_:)`
* `firstMap(_:)`
### Comparison with other languages
**Scala**: Scala provides a `collectFirst` function that finds the first element
in a collection for which a partial function is defined.
**Haskell**: Haskell includes the `firstJust` method, which has the same
semantics as the `firstNonNil(_:)` method.
**Rust**: Rust includes the `find_map` method, which has the same semantics as
the `firstNonNil(_:)` method.
**Scala**: Scala includes the `collectFirst` method, which has the same
semantics as the `firstNonNil(_:)` method.
+4 -9
View File
@@ -3,21 +3,16 @@
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Reductions.swift) |
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/ReductionsTests.swift)]
Produces a sequence of values.
This has the behaviour of reduce, but also returns all intermediate results.
Produces all the intermediate results of reducing a sequence's elements using a closure.
```swift
let exclusiveRunningTotal = (1...5).reductions(0, +)
print(exclusiveRunningTotal)
// prints [0, 1, 3, 6, 10, 15]
var value = 0
let intoRunningTotal = (1...5).reductions(into: &value, +=)
let intoRunningTotal = (1...5).reductions(into: 0, +=)
print(intoRunningTotal)
// prints [0, 1, 3, 6, 10, 15]
print(value)
// prints 15
let inclusiveRunningTotal = (1...5).reductions(+)
print(inclusiveRunningTotal)
@@ -38,7 +33,7 @@ extension LazySequenceProtocol {
) -> ExclusiveReductions<Result, Self>
public func reductions<Result>(
into initial: inout Result,
into initial: Result,
_ transform: @escaping (inout Result, Element) -> Void
) -> ExclusiveReductions<Result, Self>
@@ -57,7 +52,7 @@ extension Sequence {
) rethrows -> [Result]
public func reductions<Result>(
into initial: inout Result,
into initial: Result,
_ transform: (inout Result, Element) throws -> Void
) rethrows -> [Result]
+5 -3
View File
@@ -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.
- [`randomStableSample(count:)`, `randomStableSample(count:using:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/RandomSampling.md): Randomly selects a specific number of elements from a collection, preserving their original relative order.
- [`striding(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Stride.md): Returns every nth element of a collection.
- [`suffix(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Suffix.md): Returns the suffix of a collection where all element pass a given predicate.
- [`trimming(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Trim.md): Returns a slice by trimming elements from a collection's start and end.
- [`uniqued()`, `uniqued(on:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Unique.md): The unique elements of a collection, preserving their order.
#### Partial sorting
@@ -37,12 +39,12 @@ Read more about the package, and the intent behind it, in the [announcement on s
#### Other useful operations
- [`chunked(by:)`, `chunked(on:)`, `chunks(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Chunked.md): Eager and lazy operations that break a collection into chunks based on either a binary predicate or when the result of a projection changes or chunks of a given count.
- [`firstNonNil(_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/FirstNonNil.md): Returns the first non-`nil` result from transforming a sequence's elements.
- [`indexed()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Indexed.md): Iterate over tuples of a collection's indices and elements.
- [`interspersed(with:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Intersperse.md): Place a value between every two elements of a sequence.
- [`trimming(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Trim.md): Returns a slice by trimming elements from a collection's start and end.
- [`windows(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Windows.md): Breaks a collection into overlapping subsequences where elements are slices from the original collection.
- [`striding(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Stride.md): Returns every nth element of a collection.
- [`reductions(_:)`, `reductions(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Reductions.md): Returns all the intermediate states of reducing the elements of a sequence or collection.
- [`split(maxSplits:omittingEmptySubsequences:whereSeparator)`, `split(separator:maxSplits:omittingEmptySubsequences)`](https://github.com/apple/swift-algorithms/blob/main/Guides/LazySplit.md): Lazy versions of the Standard Library's eager operations that split sequences and collections into subsequences separated by the specified separator element.
- [`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
+22 -7
View File
@@ -14,15 +14,30 @@
//===----------------------------------------------------------------------===//
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>(
_ transform: (Element) throws -> Result?
) rethrows -> Result? {
for value in self {
if let value = try transform(value) {
return value
}
}
return nil
for value in self {
if let value = try transform(value) {
return value
}
}
return nil
}
}
+9 -12
View File
@@ -39,9 +39,7 @@ extension LazySequenceProtocol {
_ initial: Result,
_ transform: @escaping (Result, Element) -> Result
) -> ExclusiveReductions<Result, Self> {
var result = initial
return reductions(into: &result) { result, element in
return reductions(into: initial) { result, element in
result = transform(result, element)
}
}
@@ -69,7 +67,7 @@ extension LazySequenceProtocol {
/// - Complexity: O(1)
@inlinable
public func reductions<Result>(
into initial: inout Result,
into initial: Result,
_ transform: @escaping (inout Result, Element) -> Void
) -> ExclusiveReductions<Result, Self> {
ExclusiveReductions(base: self, initial: initial, transform: transform)
@@ -117,9 +115,7 @@ extension Sequence {
_ initial: Result,
_ transform: (Result, Element) throws -> Result
) rethrows -> [Result] {
var result = initial
return try reductions(into: &result) { result, element in
return try reductions(into: initial) { result, element in
result = try transform(result, element)
}
}
@@ -160,7 +156,7 @@ extension Sequence {
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
@inlinable
public func reductions<Result>(
into initial: inout Result,
into initial: Result,
_ transform: (inout Result, Element) throws -> Void
) rethrows -> [Result] {
@@ -168,6 +164,7 @@ extension Sequence {
output.reserveCapacity(underestimatedCount + 1)
output.append(initial)
var initial = initial
for element in self {
try transform(&initial, element)
output.append(initial)
@@ -595,10 +592,10 @@ extension LazySequenceProtocol {
@available(*, deprecated, message: "Use reductions(into:_:) instead.")
@inlinable
public func scan<Result>(
into initial: inout Result,
into initial: Result,
_ transform: @escaping (inout Result, Element) -> Void
) -> ExclusiveReductions<Result, Self> {
reductions(into: &initial, transform)
reductions(into: initial, transform)
}
}
@@ -616,10 +613,10 @@ extension Sequence {
@available(*, deprecated, message: "Use reductions(into:_:) instead.")
@inlinable
public func scan<Result>(
into initial: inout Result,
into initial: Result,
_ transform: (inout Result, Element) throws -> Void
) 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(EmptyCollection<Int>().lazy.reductions(0, +), [0])
var value = 0
XCTAssertEqual([1, 2, 3, 4].lazy.reductions(into: &value, +=), [0, 1, 3, 6, 10])
XCTAssertEqual(value, 10)
XCTAssertEqual([1, 2, 3, 4].lazy.reductions(into: 0, +=), [0, 1, 3, 6, 10])
value = 0
XCTAssertEqual([1].lazy.reductions(into: &value, +=), [0, 1])
XCTAssertEqual(value, 1)
XCTAssertEqual([1].lazy.reductions(into: 0, +=), [0, 1])
value = 0
XCTAssertEqual(EmptyCollection<Int>().lazy.reductions(into: &value, +=), [0])
XCTAssertEqual(value, 0)
XCTAssertEqual(EmptyCollection<Int>().lazy.reductions(into: 0, +=), [0])
XCTAssertLazySequence((1...).prefix(1).lazy.reductions(0, +))
XCTAssertLazySequence([1].lazy.reductions(0, +))
@@ -49,17 +43,11 @@ final class ReductionsTests: XCTestCase {
XCTAssertEqual([1].reductions(0, +), [0, 1])
XCTAssertEqual(EmptyCollection<Int>().reductions(0, +), [0])
var value = 0
XCTAssertEqual([1, 2, 3, 4].reductions(into: &value, +=), [0, 1, 3, 6, 10])
XCTAssertEqual(value, 10)
XCTAssertEqual([1, 2, 3, 4].reductions(into: 0, +=), [0, 1, 3, 6, 10])
value = 0
XCTAssertEqual([1].reductions(into: &value, +=), [0, 1])
XCTAssertEqual(value, 1)
XCTAssertEqual([1].reductions(into: 0, +=), [0, 1])
value = 0
XCTAssertEqual(EmptyCollection<Int>().reductions(into: &value, +=), [0])
XCTAssertEqual(value, 0)
XCTAssertEqual(EmptyCollection<Int>().reductions(into: 0, +=), [0])
XCTAssertNoThrow(try [].reductions(0) { _, _ in throw TestError() })
XCTAssertThrowsError(try [1].reductions(0) { _, _ in throw TestError() })