Skip to content

Instantly share code, notes, and snippets.

@71
Created May 21, 2020 20:16
Show Gist options
  • Save 71/efaf1498a717f6e665c894eb4c038025 to your computer and use it in GitHub Desktop.
Save 71/efaf1498a717f6e665c894eb4c038025 to your computer and use it in GitHub Desktop.
call/cc in Go
package main
// For lack of actual generics...
type Input interface{}
type Output interface{}
// CallWithCurrentContinuation returns a function k that can be used to invoke a
// continuation-passing-style function f as if it was a direct-style function.
func CallWithCurrentContinuation(f func(input Input, k func(output Output))) func(input Input) Output {
return func(input Input) Output {
var wg sync.WaitGroup
var output Output
wg.Add(1)
f(input, func(x Output) {
output = x
wg.Done()
})
wg.Wait()
return output
}
}
func PerformExpensiveComputation(x Input, cb func(y Output)) {
// ...
cb(42)
}
var PerformExpensiveComputationSync func(input Input) Output = CallWithCurrentContinuation(PerformExpensiveComputation)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment