Skip to content

Instantly share code, notes, and snippets.

@shawnsmithdev
Created May 28, 2016 06:33
Show Gist options
  • Save shawnsmithdev/8d077985c51301ad6867a81309678eff to your computer and use it in GitHub Desktop.
Save shawnsmithdev/8d077985c51301ad6867a81309678eff to your computer and use it in GitHub Desktop.
A Y Combinator in go
package main
import (
"fmt"
)
// A Y Combinator (Only for func(int) int, so not *the* y combinator)
func Y(f func(func(int) int) func(int) int) func(int) int {
return f(func(x int) int {
return Y(f)(x)
})
}
func nearFactorial(f func(int) int) func(int) int {
return func(n int) int {
if n == 0 {
return 1
}
return n * f(n-1)
}
}
func main() {
factorial := Y(nearFactorial)
for i := 0; i < 20; i++ {
fmt.Printf("%v! = %v\n", i, factorial(i))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment