Skip to content

Instantly share code, notes, and snippets.

@codegod100
Last active June 12, 2021 19:24
Show Gist options
  • Select an option

  • Save codegod100/a8fe70e142b9e9fd6da443711a4cf2aa to your computer and use it in GitHub Desktop.

Select an option

Save codegod100/a8fe70e142b9e9fd6da443711a4cf2aa to your computer and use it in GitHub Desktop.
church numerals
function church(n){
return function(f){
return function(x){
let res = x
for(let i=0;i<n;i++){
res = f(res)
}
return res
}
}
}
function unchurch(cn){
return cn(function(x){return x+1})(0)
}
const succ = function(n){
return function(f){
return function(x){
let t1 = n(f)
let t2 = t1(x)
let t3 = f(t2)
return t3
}
}
}
const plus = function(m){
return function(n){
let t1 = n(succ)
let t2 = t1(m)
return t2
}
}
const mult = function(m){
return function(n){
return function(f){
let t1 = n(f)
return m(t1)
}
}
}
const pred = function(n){
return function(f){
return function(x){
let t1 = function(g){
return function(h){
let t1 = g(f)
return h(t1)
}
}
let t2 = function(u){
return x
}
let t3 = function(u){
return u
}
let t4 = n(t1)
let t5 = t4(t2)
let t6 = t5(t3)
return t6
}
}
}
const minus = function(m){
return function(n){
let t1 = n(pred)
return t1(m)
}
}
let zero = church(0)
let one = succ(zero)
let two = church(2)
let three = plus(one)(two)
let nine = mult(three)(three)
let seven = pred(church(8))
let four = minus(church(10))(church(6))
console.log(unchurch(one))
console.log(unchurch(three))
console.log(unchurch(nine))
console.log(unchurch(seven))
console.log(unchurch(four))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment