Skip to content

Instantly share code, notes, and snippets.

@acamino
Created November 7, 2018 18:27
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 acamino/b94d7c6e454768a5a5639b313cf72953 to your computer and use it in GitHub Desktop.
Save acamino/b94d7c6e454768a5a5639b313cf72953 to your computer and use it in GitHub Desktop.
Factorial defined in terms of lambda calculus.
# Factorial
# Keep in mind we want to remove assignment.
ZERO = ->(_) { ->(x) { x } }
# ONE = ->(f) { ->(x) { f[x] } }
TWO = ->(f) { ->(x) { f[f[x]] } }
THREE = ->(f) { ->(x) { f[f[f[x]]] } }
ADD0 = ->(n) { ->(f) { ->(x) { n[f][x] } } }
SUCC = ->(n) { ->(f) { ->(x) { f[n[f][x]] } } }
ADD = ->(n) { ->(m) { n[SUCC][m] } }
MULT = ->(n) { ->(m) { n[->(acc) { ADD[m][acc]}][ZERO]} }
ID = ->(x) { x }
TRUTHY = ->(t) { ->(f) { t[ID] } }
FALSEY = ->(t) { ->(f) { f[ID] } }
IF = ->(cond) { ->(t) { ->(f) { cond[t][f] } } }
PRED = ->(n) {
->(f) {
->(x) {
n[
->(g) { ->(h) { h[g[f]] } }
][
->(u) { x }
][
->(u) { u }
]
}
}
}
IS_ZERO = ->(n) { n[->(x) { FALSEY } ][TRUTHY] }
SIX = SUCC[SUCC[SUCC[SUCC[SUCC[SUCC[ZERO]]]]]]
puts(
->(fn) {
->(n) {
IF[
IS_ZERO[n]
][
->(_) { ->(f) { ->(x) { f[x] } } }
][
->(_) { MULT[n][fn[fn][PRED[n]]] }
]
}
}[
->(fn) {
->(n) {
IF[
IS_ZERO[n]
][
->(_) { ->(f) { ->(x) { f[x] } } }
][
->(_) { MULT[n][fn[fn][PRED[n]]] }
]
}
}
][
SIX
][->(x) { x + 1}][0]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment