Created
February 27, 2016 01:58
-
-
Save DianQK/f7c35f1754a8a592c525 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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