-
-
Save keyz/344f73018298cfa2135c to your computer and use it in GitHub Desktop.
Y Combinator in R
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
## 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