Last active
February 13, 2020 23:02
-
-
Save mpreu/5c47d4301982851502c87dbfc02b104e to your computer and use it in GitHub Desktop.
How to implement recursion with the Y combinator in GNU R using the recursive addition as an example. Originates from this blog post: https://www.matthiaspreu.com/posts/lambda-calculus-recursion/.
This file contains hidden or 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
# Part of a blog post about lambda calculus on my website: | |
# https://www.matthiaspreu.com/posts/lambda-calculus-recursion/ | |
# Y combinator based on the expression: | |
# | |
# Y = λf.(λx.f(xx))(λx.f(xx)) | |
Y <- function(f) { | |
fxx <- function(x) { f((x)(x)) } | |
(fxx)(fxx) | |
} | |
# Abstracted addition function expecting | |
# the real addition function as a parameter. | |
# Based on the expression: | |
# | |
# λ ADD xy.Z y x SUCC((ADD x (PRED y))) | |
add_generator <- function(add) { | |
function(x,y) { | |
if (y == 0) { | |
x | |
} else { | |
add(x,y-1) + 1 | |
} | |
} | |
} | |
# Extract our real addition function as the fixed | |
# point of add_generator. | |
add <- function(x,y) { Y(add_generator)(x,y) } | |
# Example application | |
print(add(2,2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment