Skip to content

Instantly share code, notes, and snippets.

@DianQK

DianQK/Async.swift

Created Feb 27, 2016
Embed
What would you like to do?
enum Result<T> {
case Success(T)
case Failure(ErrorType)
}
extension Result {
static func unit(x: T) -> Result<T> {
return .Success(x)
}
func map<U>(f: T throws -> U) -> Result<U> {
return flatMap { .unit(try f($0)) }
}
func flatMap<U>(f:T throws -> Result<U>) -> Result<U> {
switch self {
case .Success(let value):
do {
return try f(value)
} catch let e {
return .Failure(e)
}
case .Failure(let e):
return .Failure(e)
}
}
}
struct Async<T> {
let trunk: (Result<T> -> Void) -> Void
init(function: (Result<T> -> Void) -> Void) {
trunk = function
}
func execute(callBack: Result<T> -> Void) {
trunk(callBack)
}
}
extension Async {
static func unit(x: T) -> Async<T> {
return Async { $0(.Success(x)) }
}
func map<U>(f: T throws -> U) -> Async<U> {
return flatMap { .unit(try f($0)) }
}
func flatMap<U>(f: T throws -> Async<U>) -> Async<U> {
return Async<U> { cont in
self.execute {
switch $0.map(f) {
case .Success(let async):
async.execute(cont)
case .Failure(let error):
cont(.Failure(error))
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment