Created
May 21, 2020 20:16
-
-
Save 71/efaf1498a717f6e665c894eb4c038025 to your computer and use it in GitHub Desktop.
call/cc in Go
This file contains hidden or 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
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