Last active
December 21, 2015 19:19
-
-
Save tristanwietsma/6353538 to your computer and use it in GitHub Desktop.
Faking tail call optimization with concurrency
This file contains 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 | |
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