Skip to content

Instantly share code, notes, and snippets.

@bkyrlach
Last active December 11, 2015 07:48
Show Gist options
  • Save bkyrlach/4568770 to your computer and use it in GitHub Desktop.
Save bkyrlach/4568770 to your computer and use it in GitHub Desktop.
A paltry attempt to understand lambda calculus...
class LAMBDA(f: LAMBDA => LAMBDA) {
def apply(l: LAMBDA): LAMBDA = f(l)
}
object Functions {
val identity = new LAMBDA(l => l)
val zero = new LAMBDA(f => identity)
val succ = new LAMBDA(n => new LAMBDA(f => new LAMBDA(x => f((n(f)(x))))))
val pred = new LAMBDA(n => new LAMBDA(f => new LAMBDA(x => n(new LAMBDA(g => new LAMBDA(h => h(g(f)))))(new LAMBDA(u => x))(new LAMBDA(u => u)))))
val one = succ(zero)
val two = succ(one)
val three = succ(two)
val four = succ(three)
val FALSE = zero
val TRUE = new LAMBDA(l => new LAMBDA(r => r))
val isZero = new LAMBDA(f => f(new LAMBDA(x => FALSE))(TRUE))
val IF = new LAMBDA(l => new LAMBDA(r => new LAMBDA(t => t(l)(r))))
def g(n: LAMBDA): Int = if(isZero(n) == TRUE) 0 else 1 + g(pred(n))
}
object Program1 {
import Functions._
def main(args: Array[String]): Unit = {
println(isZero(zero) == TRUE)
println(isZero(one) == FALSE)
println(IF(one)(zero)(TRUE) == one)
println(IF(one)(zero)(FALSE) == zero)
pred(two)(new LAMBDA(f => {
println("1"); identity
}))(identity)
println(g(three))
}
}
@bkyrlach
Copy link
Author

This code currently doesn't work. I'll update it once I spot the mistake.

@bkyrlach
Copy link
Author

Fixed now, but probably could be expressed better.

@bkyrlach
Copy link
Author

Minor syntax enhancement... can't go all the way due to what appear to be limitations in Scala's type system.

@bkyrlach
Copy link
Author

Thanks to my friend @crkirkendall I have finally gained some understanding.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment