Skip to content

Instantly share code, notes, and snippets.

@DianQK
Created February 27, 2016 01:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DianQK/f7c35f1754a8a592c525 to your computer and use it in GitHub Desktop.
Save DianQK/f7c35f1754a8a592c525 to your computer and use it in GitHub Desktop.
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