Skip to content

Instantly share code, notes, and snippets.

@y-yu
Created January 17, 2020 19:52
Show Gist options
  • Save y-yu/37fd5401785db22b211da54f60517a48 to your computer and use it in GitHub Desktop.
Save y-yu/37fd5401785db22b211da54f60517a48 to your computer and use it in GitHub Desktop.
struct Cont<A, B> {
var run: ((A) -> B) -> B
var flatMap: (A) -> Cont<A, B> {
get {
fatalError()
}
_modify {
let that = self
var f: (A) -> Cont<A, B> = { (a: A) -> Cont<A, B> in that }
yield &f
run = { (k: (A) -> B) -> B in that.run({ (a: A) -> B in f(a).run(k) }) }
}
}
}
var a = Cont<String, String>(
run: { (k) in k( "a↓ ") + "f!" }
)
a.flatMap = { (x) in
Cont(
run: { (k) in k(x + "b↓ ") + "e↑ " }
)
}
a.flatMap = { (x) in
Cont(
run: { (k) in k(x + "c→ ") + "d↑ " }
)
}
func identity<A>(_ a: A) -> A {
return a
}
print(a.run(identity))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment