Last active
August 29, 2015 14:08
-
-
Save chriseidhof/dbaaaa3e80497c233e4c to your computer and use it in GitHub Desktop.
Parallel API
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 Either<A,B> { | |
case Left(A) | |
case Right(B) | |
} | |
// Not sure about which cases this should have... | |
enum Async<A> { | |
case Delayed(() -> Async<A>) | |
case Result(A) | |
case Failure(NSError) | |
} | |
// This is the most important operator, sequencing things | |
infix operator >>= { associativity left } | |
func >>=<A, B>(l: Async<A>, r: A -> Async<B>) -> Async<B> { | |
switch l { | |
case .Failure(let e): return .Failure(e) | |
case .Result(let x): return r(x) | |
case .Delayed(let f): return Async.Delayed { | |
switch f() { | |
case .Result(let x): return r(x) | |
case .Failure(let e): return Async.Failure(e) | |
case .Delayed(let f2): return f2() >>= r | |
} | |
} | |
} | |
} | |
infix operator <|> { associativity left } | |
// This operator runs both its operands in parallel, returning the result of the first one that succeeds, and cancelling the second one. | |
func <|><A>(Async<A>, Async<A>) -> Async<A> { | |
return Async.Failure(NSError()) // TODO | |
} | |
func getURL(url: NSURL) -> Async<NSData> { | |
return Async.Failure(NSError()) // TODO | |
} | |
func parseJSON(data: NSData) -> Async<AnyObject> { | |
return Async.Failure(NSError()) // TODO | |
} | |
func timeOut<A>(seconds: Double) -> Async<A> { | |
return Async.Failure(NSError()) // TODO | |
} | |
func background<A,B>(A -> B) -> A -> Async<B> { return { _ in Async.Failure(NSError()) } } | |
func main<A,B>(A -> B) -> A -> Async<B> { return { _ in Async.Failure(NSError()) } } | |
let processJSON : AnyObject -> Async<[String:Int]> = background {(json: AnyObject) in | |
// Process json | |
return ["Hello": 1] | |
} | |
let result = getURL(NSURL(string: "http://www.nu.nl")!) >>= parseJSON >>= processJSON | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment