Created
November 7, 2018 18:27
-
-
Save acamino/b94d7c6e454768a5a5639b313cf72953 to your computer and use it in GitHub Desktop.
Factorial defined in terms of lambda calculus.
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
# 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