From 001247f8a55429ecce9082603e98b9a486e6dff5 Mon Sep 17 00:00:00 2001 From: Tim Vermeulen Date: Mon, 29 Mar 2021 19:18:56 +0200 Subject: [PATCH] Expand the `firstNonNil(_:)` docs (#115) * Fix indentation * Improve documentation --- Guides/FirstNonNil.md | 78 +++++++++++++++++++++------- Sources/Algorithms/FirstNonNil.swift | 29 ++++++++--- 2 files changed, 82 insertions(+), 25 deletions(-) diff --git a/Guides/FirstNonNil.md b/Guides/FirstNonNil.md index 16e41a8..26ed376 100644 --- a/Guides/FirstNonNil.md +++ b/Guides/FirstNonNil.md @@ -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(_ transform: (Element) throws -> Result?) - rethrows -> Result? + func firstNonNil( + _ 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. diff --git a/Sources/Algorithms/FirstNonNil.swift b/Sources/Algorithms/FirstNonNil.swift index 55258e6..0c15c83 100644 --- a/Sources/Algorithms/FirstNonNil.swift +++ b/Sources/Algorithms/FirstNonNil.swift @@ -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( _ 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 + } }