Skip to content

Instantly share code, notes, and snippets.

@iamnoah
Created April 9, 2010 14:44
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 iamnoah/361233 to your computer and use it in GitHub Desktop.
Save iamnoah/361233 to your computer and use it in GitHub Desktop.
// Church Encoding in Groovy
// Translated from http://meta-meta.blogspot.com/2007/06/church-code.html
def partial(c) {
return { a -> { b -> c(a,b) } }
}
T = partial { a,b -> a }
F = partial { a,b -> b }
def toBool(f) {
f(true)(false)
}
cand = partial { a,b -> a(b)(a) }
cor = partial { a,b -> a(a)(b) }
def TT(fn) {
[[F,F],[F,T],[T,F],[T,T]].collect { it ->
toBool( fn(it[0])(it[1]) )
}
}
// print truth tables to verify
println " \tFF\tFT\tTF\tTT"
println "cand:\t" + TT(cand).join("\t")
println "cor: \t" + TT(cor).join("\t")
pair = partial { a,b -> { p -> p(a)(b) } }
cfst = { pair -> pair(T) }
csnd = { pair -> pair(F) }
def toNum(f) {
f({ it + 1 })(0)
}
zero = partial { f,x -> x }
succ = { s -> partial { f,x -> f(s(f)(x)) } }
one = succ(zero)
two = succ(one)
three = succ(two)
plus = partial { a,b -> partial { f,x -> a(f)(b(f)(x)) } }
def toChurchNum(i, num = zero) {
if(i <= 0) return num
return toChurchNum(i-1,succ(num))
}
just = { v -> partial { f, x -> f(v) } }
nothing = partial { f,x-> x } // F
left = { v -> partial { f,g -> f(v) } }
right = { v -> partial { f,g -> g(v) } }
cons = partial { h,t-> partial { cf,ev-> cf(h)(t) } }
empty = partial { cf, ev -> ev } // F
car = { it(T)(null) } // first
cdr = { it(F)(null) } // rest
map = partial { f,l -> l( partial { h,t-> cons(f(h))(map(f)(t)) })(empty) }
list = cons(one)(cons(two)(cons(three)(empty)))
toNum(car(map({plus(it)(two)})(list))) // 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment