Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for higher order functions that can throw #219

Open
torstenlehmann opened this issue Apr 24, 2017 · 1 comment
Open

Support for higher order functions that can throw #219

torstenlehmann opened this issue Apr 24, 2017 · 1 comment

Comments

@torstenlehmann
Copy link

torstenlehmann commented Apr 24, 2017

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?

@torstenlehmann torstenlehmann changed the title Support for higher order functions that can throw. Support for higher order functions that can throw Apr 24, 2017
@thedavidharris
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants