profile
viewpoint

Ask questionsA `first` operator that returns the first non-nil transformed value

I found myself often having to find the first element in an array that passes an optional initialiser. If I wanted to stick to a purely functional paradigm (which I do, I'm a zealot) I need to do some pretty not-ideal transforms to allow this behaviour without defining a new function.

let value = ["Hello", "10"].lazy.map(Int.init).first { $0 != nil }.flatMap { $0 }

This could be trivialised with the following (naive) implementation.

public extension Sequence {
    /// Returns the first element in `self` that `transform` maps to a `.some`.
    func first<Result>(of transform: (Element) throws -> Result?) rethrows -> Result? {
        for value in self {
            if let value = try transform(value) {
                return value
            }
        }
        return nil
    }
}
apple/swift-algorithms

Answer questions pyrtsa

@ktoso I think you mixed up the type signatures? And if you did, isn't func collect<R>(_ transform: (Element) -> R?) -> [R] what we already know as compactMap(_:)?

useful!

Related questions

No questions were found.
source:https://uonfu.com/
Github User Rank List