News for hackers. Stuff that matters.
Re:The power of Result types in Swift by KirinDave on Sunday June 17, 2018 @11:18PM (#17335797)
The tricky part of this approach comes when you extend it. Let's say we have two functions and we'd like to combine them and return a third.

    typealias Handler1 = (Result<Data, LoadError> -> Void)
    typealias Handler2 = (Result<Address, IndexError> -> Void)

    func load(addr: Address, then handler: @escaping Handler1) { ... }
    func lookup(name: string, then handler: @escaping Handler2) { ... }


    // What would the type of Handler3 be?
    func loadDefault(then handler: @escaping Handler3) {
       lookup("default") { result in
           switch result {
           case .success(let address):
               load(address) { result2 in
                   switch result2 {
                       case .success(let data):
                           // Happy path
                       case .failure(let error):
                           // We have a load error for handler3
               }
           case .failure(let outerError):
               // ERROR: We have a lookup error for handler3
           }
        }
     }
     // P.S., don't complain about syntax I really don't know swift :P
Handler3's type is actually the sum of LoadError and IndexError. This is sort of a non-trivial problem for a lot of use cases of Either. Monadic and Railway Either programming typically solve this problem by saying, "Fine well then every single Either/Result in the chain needs to be of the same type, which includes a unified error type." In this article's case, I guess we could appeal to Swift's binding to FoundationKit to lift up NSError? Sure! That'll compile! Maybe there is a Compound Type thing? It will probably compile but it'll shape your handler in weird ways.

It still seems pretty unsatisfying. The point here was to make it easy to work out what errors we should handle, but now we need an explosion of combination types (unique to each call graph in this case, wow!) Modern Haskell, which along with ML pioneered these style of, has some slick type machinery tricks to deal with this that are not well supported yet (even type lists are not a slam dunk because we need something that's order-insensitive). Most folks will be required to make a new ad-hoc sum type (like Result, but EitherError<Error1, Error2>), and then have to pattern match on that to handle errors.

But at the end of the day, even Haskell with all its principle has try/catch statements in IO and an exception hierarchy. In fact, it's considered best practice for production code to avoid giving the appearance that Either can capture all your errors (since it seldom can): https://www.fpcomplete.com/blog/2016/11/exceptions-best-prac...

Which is not to say Either's (and Railway programming's) "Sum-type errors") aren't a substantial improvement over special return values or Common Lisp/Go's product-style return values. They are. But sadly they can't really get you away from exception handling when you start interacting with the "real" world as the examples here do. It's a win for things like HTTP responses or decoding libraries.

Re:The power of Result types in Swift by wereHamster on Sunday June 17, 2018 @11:53PM (#17335923)
You can improve that code by having a single error type. Either by returning the same error from both handlers or having an error sum type which contains both errors. You probably don't really care about the exact error that can be thrown by either handler, you just need enough information to display a sensible message to the user. NSError may be just enough for that purpose!

After doing that, the type of Handler3 can be had as Result<Tuple<Data, Address>, NSError>, for example. And how do you combine the two results into the Tuple? That's an applicative, I'm sure swift provides combinators to do just that.

Re:The power of Result types in Swift by taeric on Monday June 18, 2018 @12:20AM (#17335999)
Didn't the post you are responding to say that? I suspect you didn't read past the example.

The problem comes because you have to either use a single error for two parts or deal with a tough explosion of types. No?

Re:The power of Result types in Swift by masklinn on Monday June 18, 2018 @06:26AM (#17337060)
There are known solutions to this problem: you can type-erase to a single supertype (e.g. Error/NSError[0]) or convert from the third-party's type to a first-party type[1] for instance.

[0] https://developer.apple.com/documentation/swift/error

[1] https://boats.gitlab.io/failure/

Re:The power of Result types in Swift by KirinDave on Monday June 18, 2018 @11:04AM (#17338756)
It's sort of amazing that you're replying to a post suggesting something I suggested, by re-suggesting what all 3 posts prior to you suggested.

But as I've said, yeah you can do this. But it's unfortunate because it destroys a lot of information that's useful in the type signature. Haskell does this with exception hierarchies and some clever runtime casting attempts, but even that has ergonomic issues.

What'd be really amazing is if we could get the totality checking of pattern matching but also the composability of exception handlers, and that's what the next generation of error handling primitives are trying to do.

Re:The power of Result types in Swift by KirinDave on Monday June 18, 2018 @01:44AM (#17336199)
> the type of Handler3 can be had as Result<Tuple<Data, Address>, NSError>,

The combination of data and lookup is more like data(lookup(default)), which in haskell (assuming we could encode the error type neatly):

    load =<< lookup "default".
So Result3's first parameter is of type Data.

> You probably don't really care about the exact error that can be thrown by either handler, you just need enough information to display a sensible message to the user.

Please consider looking for the part of the article we're discussing where it says, "However, adding that extra type information to our result type does have some nice benefits - for example, it lets us specifically handle all possible errors at the call site, like this"

Ultimately we'd like to get to where the compiler can do at least a rudimentary totality check on the error handler.

P.S., I know my prose is rambling and my code is overly verbose, but please consider how it makes me feel when you give me suggestions I myself discussed in the prior post.

Re:The power of Result types in Swift by cousin_it on Monday June 18, 2018 @07:20AM (#17337322)
I think "sum-type errors" are the wrong default. They force you to deal with the bureaucracy of different error types, which is useless because error handling almost never cares about error type. And they don't give you a stack trace, which is a lifesaver for development and debugging. Plain old unchecked exceptions work better. Probably cheaper too, because sum types require wrapping and unwrapping at each step, while exceptions can be very cheap when not thrown.
Re:The power of Result types in Swift by KirinDave on Monday June 18, 2018 @10:55AM (#17338685)
> I think "sum-type errors" are the wrong default. They force you to deal with the bureaucracy of different error types, which is useless because error handling almost never cares about error type.

I hear this parroted a lot, and I really don't get it. When an exception happens, you can't resume control flow (unless you're in Common Lisp, which has an objectively better system for exceptions than any we use). In that case, you're right that specific type and details don't matter.

But if you get the failure value back as part of the control flow with a precise type then you can actually recover from it. People quote the Erlang philosophy out-of-context suggesting this is Actually Always Bad. It's not! You might want to: provide a default value for a server (bind to 127.0.0.1 or 0.0.0.0), synthesize a default templated configuration file, propose a valid algorithm over a forbidden one in a cryptographic negotiation, etc.

> Plain old unchecked exceptions work better. Probably cheaper too, because sum types require wrapping and unwrapping at each step, while exceptions can be very cheap when not thrown.

I'd be surprised if that was the case. Stack unwinding and introspection looking for handlers is infamously expensive whereas reading fields from a struct on the stack is seldom considered very expensive. Even if you do have an on-heap indirection that breaks locality, it's not like firing off a random class handlers further up the stack is gonna be BETTER for locality. Given that `finally` exists and objects have destructors, an exception up-stack is often a lot more code than it looks like.

Re:The power of Result types in Swift by cousin_it on Monday June 18, 2018 @01:03PM (#17339788)
Yeah, agreed that exceptions make the exceptional path more expensive. But I think the normal path is cheaper.

I'm not sold on resumable exceptions. It makes more sense to pass default values directly. Have you seen this bit in Stroustrup's book: http://www.cpptips.com/term_except

Re:The power of Result types in Swift by KirinDave on Monday June 18, 2018 @02:34PM (#17340530)
Actually, I'm not entirely right here. Joe Groff caught up with me on twitter and explained to me that because Swift requires you to check exceptions, it actually generates static logic at the call site. This means handlers have a cost on both sides of the "railway", but it means that exception handling has a fairly optimal codepath.

It'll still be cheaper to do a simple pattern match into a struct for complex handlers, but for depth 1 they should essentially be identical. That's a very interesting tradeoff for the Swift compiler!