Created
May 3, 2012 01:50
-
-
Save jonbodner/2582487 to your computer and use it in GitHub Desktop.
Y Combinator in Go
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" | |
//based on code from http://www.arcfn.com/2009/03/y-combinator-in-arc-and-java.html | |
type Func func (interface{}) interface{} | |
type FuncToFunc func (Func) Func | |
type FuncToTFunc func (FuncToTFunc) Func | |
func Y(r FuncToFunc) Func { | |
return func(f FuncToTFunc) Func { | |
return f(f) | |
}(func(f FuncToTFunc) Func { | |
return r(func(x interface{}) interface{} { | |
return f(f)(x) | |
}) | |
}) | |
} | |
func main() { | |
fmt.Println(Y(func(f Func) Func { | |
return func(n interface{}) interface{} { | |
nn := n.(int) | |
if nn == 0 { | |
return 1 | |
} | |
return nn * (f(nn-1)).(int) | |
} | |
})(5)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment