antitypical / Result

Swift type modelling the success/failure of arbitrary operations.
MIT License
2.51k stars 227 forks source link

Support for higher order functions that can throw #219

Open torstenlehmann opened 7 years ago

torstenlehmann commented 7 years ago

Thanks for the work on this type. I try to replace Swift throws with Result in one of my projects, but on every higher order function I'm stopped. The project depends on the behavior of map and that it's transform function can throw. So I wrote a map that can do this with Result. Here is my implementation (not that functional):

extension Sequence {

    /// Returns an array containing the results of mapping the given closure
    /// over the sequence's elements.
    ///
    /// - Parameter transform: A mapping closure. `transform` accepts an
    ///   element of this sequence as its parameter and returns a transformed
    ///   value of the same or of a different type wrapped in a `Result`.
    /// - Returns: A `Result` containing an array of the transformed elements of this
    ///   sequence or the error of the first `failure` that occured by applying `transform`.
    func tryMap<T, E>(transform: (Self.Iterator.Element) -> Result<T, E>) -> Result<[T], E> {

        var transformedElements = [T]()
        for element in self {
            switch transform(element) {
            case .success(let transformed):
                transformedElements.append(transformed)
            case .failure(let error):
                return .failure(error)
            }
        }
        return .success(transformedElements)

    }

}

So without a Result version of all these standard library functions that can throw I doubt that I can use the Result type to it's full extend. Is there some library that can help me out here?

thedavidharris commented 5 years ago

Kind of bumping this. It would make sense for the map/flatMap functions to be rethrowing and in the case of an error thrown, to make it return a failure. Not sure how typed errors would affect this, but it would also behave more like the Swift STL handles its higher order functions.