这是一个反例:在λ演算中,每种数据类型都可以归结为函数。λ演算没有节点或指针,它仅有的就是函数,因此必须使用函数来实现。
这是使用ECMAScript编写的将布尔值编码为函数的示例:
const T = (thn, _ ) => thn,
F = (_ , els) => els,
or = (a , b ) => a(a, b),
and = (a , b ) => a(b, a),
not = a => a(F, T),
xor = (a , b ) => a(not(b), b),
iff = (cnd, thn, els) => cnd(thn, els)();
这是一个缺点列表:
const cons = (hd, tl) => which => which(hd, tl),
first = list => list(T),
rest = list => list(F);
可以将自然数实现为迭代器函数。
集合与其特征函数(即contains
方法)相同。
请注意,上面的布尔值的Church Encoding实际上是在诸如Smalltalk之类的OO语言中实现条件的方式,这些语言不具有布尔值,条件或循环作为语言构造,而仅将它们实现为库功能。Scala中的一个示例:
sealed abstract trait Boolean {
def apply[T, U <: T, V <: T](thn: => U)(els: => V): T
def ∧(other: => Boolean): Boolean
def ∨(other: => Boolean): Boolean
val ¬ : Boolean
final val unary_! = ¬
final def &(other: => Boolean) = ∧(other)
final def |(other: => Boolean) = ∨(other)
}
case object True extends Boolean {
override def apply[T, U <: T, V <: T](thn: => U)(els: => V): U = thn
override def ∧(other: => Boolean) = other
override def ∨(other: => Boolean): this.type = this
override final val ¬ = False
}
case object False extends Boolean {
override def apply[T, U <: T, V <: T](thn: => U)(els: => V): V = els
override def ∧(other: => Boolean): this.type = this
override def ∨(other: => Boolean) = other
override final val ¬ = True
}
object BooleanExtension {
import scala.language.implicitConversions
implicit def boolean2Boolean(b: => scala.Boolean) = if (b) True else False
}
import BooleanExtension._
(2 < 3) { println("2 is less than 3") } { println("2 is greater than 3") }
// 2 is less than 3