Skip to content

Instantly share code, notes, and snippets.

@tristanwietsma
Last active December 21, 2015 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tristanwietsma/6353538 to your computer and use it in GitHub Desktop.
Save tristanwietsma/6353538 to your computer and use it in GitHub Desktop.
Faking tail call optimization with concurrency
package main
import "fmt"
func Fact(k float64) float64 {
if k == 1 {
return 1
}
return k * Fact(k-1)
}
func TailFact(k, prod float64) float64 {
if k == 1 {
return prod
}
return TailFact(k-1, k*prod)
}
// This is rather sneaky...
func SneakyFact(k float64, prod float64, result chan<- float64) {
if k == 1 {
result <- prod
return
}
prod *= k
go SneakyFact(k-1, prod, result)
return
}
func main() {
//fmt.Println(Fact(1000000)) // bad
//fmt.Println(TailFact(1000000, 1)) // still bad
ch := make(chan float64, 1)
SneakyFact(1000000, 1, ch)
fmt.Println(<-ch)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment