Skip to content

Instantly share code, notes, and snippets.

@keyz
Created February 26, 2015 05:39
Show Gist options
  • Save keyz/344f73018298cfa2135c to your computer and use it in GitHub Desktop.
Save keyz/344f73018298cfa2135c to your computer and use it in GitHub Desktop.
Y Combinator in R
## fact <- function(x) {
## if (x == 1) {
## 1
## }
## else {
## x * fact(x - 1)
## }
## }
## fact(5)
## ## [1] 120
(function(f) {
(function(x) {
(x) (x)
})(function(y) {
f((function(a) {
y(y)
})(a))
})
})(function(f) {
function(n) {
if (n == 1)
1
else
n * f(n-1)
}})(5)
## [1] 120
Y <- function(f) {
(function(x) {
(x) (x)
})(function(y) {
f((function(a) {
y(y)
})(a))
} )
}
fact <- function(f) {
function(n) {
if (n == 1)
1
else
n * f(n-1)
}
}
Y(fact)(5)
## [1] 120
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment