wiki

Church encoding

Representing data as functions in the pure lambda calculus: the numeral n applies its argument n times, true and false choose between two arguments, and a pair waits for a selector. Addition, multiplication and exponentiation are one line each; the predecessor needs a trick and takes time linear in n.

Each is a fact about iteration. Applying times and then times applies it times. Iterating a total of times applies times, so multiplication is composition of numerals. And composes with itself times, which is .

A numeral can only iterate; it has no access to the number it was built from. Kleene's predecessor iterates on pairs instead, starting from .[2] After steps the pair is , and the first component is the answer:

It takes steps to go down by one.

In OCaml a numeral needs a polymorphic record field, because exp uses a numeral at a function type and pred at a pair type.

(* A numeral is "apply f n times", for every type of f. *)
type church = { run : 'a. ('a -> 'a) -> 'a -> 'a }
let zero = { run = (fun _ x -> x) }
let succ n = { run = (fun f x -> f (n.run f x)) }
let plus m n = { run = (fun f x -> m.run f (n.run f x)) }
let mult m n = { run = (fun f -> m.run (n.run f)) }
let exp m n = { run = (fun f x -> n.run m.run f x) }
(* Predecessor: iterate (a, b) -> (b, b + 1) from (0, 0), keep the first. *)
let pred n = fst (n.run (fun (_, b) -> (b, succ b)) (zero, zero))
let to_int n = n.run (( + ) 1) 0
let rec of_int k = if k = 0 then zero else succ (of_int (k - 1))
(* Booleans and pairs: a choice, and a function waiting for a selector. *)
let tru t _ = t
let fls _ f = f
let pair a b sel = sel a b

Running it.

plus 2 3 -> 5
mult 2 3 -> 6
exp 2 3 -> 8
pred 3 -> 2
pred 0 -> 0
pair 1 2 fls -> 2

Typed as , these are System F's natural numbers, and Böhm and Berarducci showed every inductive type can be encoded the same way:[3] the encoding of a value is its own fold.

see also

further reading

  1. [1]A. Church, The Calculi of Lambda-Conversion, Princeton University Press (1941).
  2. [2]S. C. Kleene, “A theory of positive integers in formal logic”, American Journal of Mathematics 57 (1935).
  3. [3]C. Böhm, A. Berarducci, “Automatic synthesis of typed Λ-programs on term algebras”, Theoretical Computer Science 39 (1985).