Created
June 23, 2015 12:32
-
-
Save ykst/55ffc1b5c0db695fdde1 to your computer and use it in GitHub Desktop.
Continuation Passing Style in Swift
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
// Poorman's continuation passing style library | |
struct Cps { | |
static func seqByIdx<E, U>(list: [(U, (E?, U) -> ()) -> ()], idx: UInt, value: U, next: (U) -> (), fail: (E) -> ()) { | |
if idx >= UInt(list.count) { | |
next(value) | |
} else { | |
list[Int(idx)](value, { (errorp: E?, result: U) -> () in | |
if let error = errorp { | |
fail(error) | |
} else { | |
Cps.seqByIdx(list, idx: idx + 1, value: result, next: next, fail: fail) | |
} | |
}) | |
} | |
} | |
static func seq<E,U>(list: [(U, (E?, U) -> ()) -> ()], value: U, _ next: (E?, U) -> ()) { | |
seqByIdx(list, idx: 0, value: value, next: { (u) -> () in | |
next(nil, u) | |
}, fail: { (e) -> () in | |
next(e, value) | |
}) | |
} | |
static func seq(list: [((Bool) -> ()) -> ()], _ next: (ok: Bool) -> ()) { | |
let adapted_list: [((), (()?, ()) ->()) -> ()] | |
adapted_list = list.map { e in { | |
(void, next) -> () in | |
e { success in | |
next(success ? nil : (), ()) | |
} | |
} | |
} | |
seqByIdx(adapted_list, idx: 0, value: (), next: { (u) -> () in | |
next(ok: true) | |
}, fail: { (e) -> () in | |
next(ok: false) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by cps