[swift-evolution] Proposal: Syntax sugar for cps or async functions similar to the "do try catch" for error handling.
Roy Fu
lingoerer at gmail.com
Sun Dec 6 03:21:15 CST 2015
Hi all,
Similar to the syntax ‘do try catch throw’ and ’throws’ for error handling, I propose another syntax for handling CPS functions or async call backs:
func someFutureWrappedFunc(input: Int) future-> String{
doSomeStaffInBackground{ (result:String) in
fulfil result
}
}
do{
let resultX = perform someFutureWrappedFunc(param)
let resultY = perform anotherFutureWrappedFunc(resultX)
let final = resultX + resultY + perform justAnotherFutureWrappedFunc(resultX)
self.someLabel.text = final
} timeout let context {
//maybe some additional information
}
the reason for this proposal is for the importance of async models in modern application architectures, and avoid such pyramids:
doSomeStaffInBackground { (resultX) -> Void in
doSomeOtherStaff { (resultY) -> Void in
if resultY.someCondition(resultX) {
evenMakesItMadness(resultY) { (final) -> Void in
//finally
}
}
}
}
For more context comparing this async syntax to the ‘do try catch’:
do try catch:
enum Result<T> {
case Success(T)
case Failure(ErrorType)
}
func flatMap<T,U> (result:Result<T>, f:T->Result<U>) -> Result<U>{
switch result{
case .Success(let v): return f(v)
case .Failure(let e): return .Failure(e)
}
}
func wrap1<T,U>(f:T throws-> U) -> T->Result<U> {
return {
do{
return try .Success(f($0))
}catch let e{
return .Failure(e)
}
}
}
func wrap2<T,U>(f:T -> Result<U>) -> T throws-> U{
return{
switch f($0){
case .Success(let v): return v
case .Failure(let e): throw e
}
}
}
async:
func flatMap<T,U> (async: (T -> Void) -> Void, f:T -> (U->Void) -> Void) -> (U -> Void) -> Void {
return{ cont in
async{ f($0)(cont) }
}
}
func wrap1<T,U>(f:T future-> U) -> T->(U->Void)->Void {
return {input in
{cont in
do{
cont(perform f(input))
}catch _{
}
}
}
}
func wrap2<T,U>(f:T -> (U->Void)->Void) -> T future-> U{
return{
f(input)({
fulfil $0
})
}
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151206/28d5ed01/attachment.html>
More information about the swift-evolution
mailing list