Skip to content

Instantly share code, notes, and snippets.

@ykst
Created June 23, 2015 12:32
Show Gist options
  • Save ykst/55ffc1b5c0db695fdde1 to your computer and use it in GitHub Desktop.
Save ykst/55ffc1b5c0db695fdde1 to your computer and use it in GitHub Desktop.
Continuation Passing Style in Swift
// 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)
})
}
}
@ykst
Copy link
Author

ykst commented Jun 23, 2015

Inspired by cps

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment