acb's technical journal

Posts matching tags 'promises'

2016/1/18

Futures/Promises in Swift, draft 1.1

With the recent open-sourcing of the Swift language and its availability (albeit piecemeal, and not quite as we know it) on Linux, I have been spending some time playing with Swift on Linux. In my opinion, it holds promise for implementing the sorts of server-side code that often runs on Linux instances; one example would be web applications. With its LLVM-based optimising compiler, strong type system and the ability to minimise the amount of mutable state (more so than, say, Python or JavaScript), it should lend itself to performant server-side code quite well.

In any case, here is the first result of my experiments in Swift on Linux: a proof of concept of Futures/Promises. It's modelled somewhat on Scala's Futures, in that Futures are monadic containers which may be transformed with map, chained with flatMap, and, should you need to go synchronous at some point, awaited.

(For those not familiar with Futures/Promises, they're a different way of organising callbacks. With callbacks, as we know them from, say, JavaScript, Objective C or Swift, if you have a possibly time-consuming process to run, you pass it a function for it to call; it returns nothing immediately, but if all goes well, your callback function gets called with the value it was waiting for. Of course, the downside of this is the building up of a “Pyramid Of Doom”, a monstrous ziggurat of curly braces, like so:

doSomething { (a) -> () in 
   doSomethingElse(a) { (b) -> () in 
     andSomethingElse(b) { (c) -> () in 
        // now handle the value here
   }
}
With Futures/Promises, you don't pass callbacks, but instead receive an opaque container type that is, at some future time, redeemable for the value of whatever computation it represents. While you don't have that value, you can do other things with it, like chain other operations on it, to be completed asynchronously. And so, our pyramid is transformed into something like;
doSomething()
  .flatMap { doSomethingElse($0) }
  .flatMap { andSomethingElse($0) }
  .onCompletion {
    // now handle the value here
  }
Which, for one, looks a bit tidier; it also allows complex chains of interdependent operations to be reasoned about more easily.)

This code is currently only a rough sketch (which is why it is a gist, rather than a repository); for one, Swift on Linux's concurrency handling still leaves a bit to be desired (Apple's libdispatch is still not available, and so this uses NSLinux, which fakes Grand Central Dispatch in a somewhat basic way, spawning a new thread for each block, and having no option of running things on the main thread; needless to say, don't use this in your financial trading app just yet.) Secondly, there is not yet a concept of a failed Promise; they may be either incomplete or successfully completed. (Whether to use a Haskell-style Either/Result value or to somehow eschew that in favour of Swift's throws mechanism is a decision to be considered when implementing the possibility of failed Promises. Also, some way of sequencing/traversing multiple Futures would be useful for nontrivial applications. Finally, there is the small matter that this code defines only a Promise type and has it do double-duty as a Future as well; which makes for simpler code, though doesn't separate the twin concerns quite as elegantly. Update: I have now updated the code to split Futures (the ones you fire off with a block to run in the background) from Promises (the ones you create and fill in yourself, giving a Future to whatever needs the result).

In any case, the typical usage would look something like the following:

// Map over a Future, then do something with its result asynchronously
var f1 = Future<Int>( future: { calculateValue(...) })
var f2 = f1.map { $0 * 2 }
f2.onComplete { doSomethingWith($0) }

// two futures chained with flatMap
var f3 = Future<String>( future: { getUserName() })
    .flatMap { Future<Int>( future: { getShoeSizeOfUser($0) } }
if let value = f3.await(3.0) {
    print("The user's shoe size is \(value)")
}

And if you want to use Promises and do the computation yourself:

func asynchronouslyComputeAFuture() -> Future<Something> {
    // create an empty Promise...
    let p = Promise<Something>()

    // start a background process which will fill the Promise in...
    dispatch_async( myQueue, {
        let result: Something = computeTheResult() // this may take a while...
        p.complete(result)
    })

    // return the Promise's Future
    return p.future()
}

This is not the only implementation of Futures/Promises for Swift, nor even one of the more complete ones. There are two others which look more complete (BrightFutures and FutureKit), though both are only available for iOS and OSX at the moment.

concurrency functional programming futures linux monads promises swift 1

This will be the comment popup.
Post a reply
Display name:

Your comment:


Please enter the text in the image above here: