Skip to content

Instantly share code, notes, and snippets.

@mpreu
Last active February 13, 2020 23:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpreu/5c47d4301982851502c87dbfc02b104e to your computer and use it in GitHub Desktop.
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/.
# 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