> On Dec 11, 2017, at 1:08 PM, Matthew Johnson via swift-evolution 
> <swift-evolution@swift.org> wrote:
> 
> It’s worth mentioning that the problem this thread is discussing can be 
> generalized to idioms / applicative.  The specific case here is for Optional 
> but many other types could benefit from an elegant syntactic solution to this 
> problem.  It might be worth exploring a more general solution.  Here’s a link 
> to how this is handled in Idris: 
> http://docs.idris-lang.org/en/latest/tutorial/interfaces.html#idiom-brackets.
> 
> Matthew

Just want to +1 a more general, less "Optional"-specific solution. You can do a 
ton of interesting things with applicative structure.

Failures from "Optional" and "throws" operate sequentially and halt 
immediately: the first "nil" or "throw" encountered prevents all work chained 
from it[1]. Another upcoming sequential operation that's worth thinking about 
in this discussion: "async"/"await".

Applicative structures throw away that sequential constraint. Let's consider 
some fun things that happen when we take it away in a couple of the examples 
above.

If "throws" were applicative, you could accumulate a bunch of errors at once.

    do { 
      // made-up syntax
      let user = User(|name: try validate(name: name), email: try 
validate(email: email)|)
    } catch {
      print(error) // .manyErrors(["name is too short", "email is invalid"])
    }

Currently, the above would halt on the first error.

If "async"/"await" were applicative, you could fire off a bunch of asynchronous 
requests in parallel.

    let homepageData = HomepageData(|await fetchCurrentUser(), await 
fetchProducts()|)

In the proposed version of "async"/"await", the above would block on 
"fetchCurrentUser()" and only call "fetchProducts()" after the response.

"Optional" would get to use that same sugar! An example from the original email:

    getPostageEstimate(|source: john.address, destination: alice.address, 
weight 2.0|)


--
[1]: "Optional" and "throws" are monadic structures and "flatMap" is the 
abstraction of this sequential operation.


Stephen

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to