Church encoding

From HandWiki
Short description: Representation of natural numbers and other data types in lambda calculus


In mathematics, Church encoding is a way of representing various data types in the lambda calculus.

In the untyped lambda calculus the only primitive data type are functions, represented by lambda abstraction terms. Types that are usually considered primitive in other notations (such as integers, Booleans, pairs, lists, and tagged unions) are not natively present.

Hence the need arises to have ways to represent the data of these varying types by lambda terms, that is, by functions that are taking functions as their arguments and are returning functions as their results.

The Church numerals are a representation of the natural numbers using lambda notation. The method is named for Alonzo Church, who first encoded data in the lambda calculus this way. It can also be extended to represent other data types in the similar spirit.

This article makes occasional use of the alternative syntax for lambda abstraction terms, where λxyz.N is abbreviated as λxyz.N, as well as the two standard combinators, Iλx.x and Kλxy.x, as needed.

Church pairs

Church pairs are the Church encoding of the pair (two-tuple) type. The pair is represented as a function that takes a function argument. The pair itself does not decide what to do with the elements of the tuple. When given its argument it will apply the argument to the two components of the pair. The definition of the pair, the select first element and the select second element functions in lambda calculus are,

pairλxy.λz.z x yfirstλp.p (λxy.x)secondλp.p (λxy.y)

For example,

first (pair a b)= (λp.p (λxy.x)) ((λxyz.z x y) a b)= (λp.p (λxy.x)) (λz.z a b)= (λz.z a b) (λxy.x)= (λxy.x) a b= a

Church Booleans

Church Booleans encode the Boolean values true and false. Some programming languages use these as an implementation model for Boolean arithmetic; examples are Smalltalk and Pico.

Boolean logic embodies a choice between two alternatives. Thus the Church encodings of true and false are functions of two parameters:

  • true chooses the first parameter ;
  • false chooses the second parameter.

The two definitions in lambda calculus are:

trueλa.λb.afalseλa.λb.b

These definitions allow predicates (i.e. functions returning logical values) to directly act as if-test clauses, so that if operator is just an identity function, and thus can be omitted. Each logical value already acts as an if, performing a choice between its two arguments. A Boolean value applied to two values returns either the first or the second value. The expression

test-clause then-clause else-clause

returns then-clause if test-clause is true, and else-clause if test-clause is false.

Because logical values like true and false choose their first or second argument, they can be combined to provide logical operators. Several implementations are usually possible, whether by directly manipulating parameters or by reducing to the more basic logical values. Here are the definitions, using the shortened notation as mentioned at the start of the article (p,q are predicates; a,b are general values):

if=λpab.p a b and=λpq.p q p=λpqab.p (q a b) bor=λpq.p p q=λpqab.p a (q a b)not=λp.pfalsetrue=λpab  .p b axor=λpq.p (not q) q=λpqab.p (q b a) (q a b)nand=λpq.not (andp q)=λpqab.p (q b a) aimplies=λpq.or (notp) q=λpqab.p (q a b) a

Some examples:

andtruefalse=(λp.λq.p q p) true false=truefalsetrue=(λa.λb.a)falsetrue=falseortruefalse=(λp.λq.p p q) (λa.λb.a) (λa.λb.b)=(λa.λb.a) (λa.λb.a) (λa.λb.b)=(λa.λb.a)=truenot2 true=(λp.λa.λb.p b a)(λa.λb.a)=λa.λb.(λa.λb.a) b a=λa.λb.(λc.b) a=λa.λb.b=falsenot1 true=(λp.p (λa.λb.b) (λa.λb.a)) (λa.λb.a)=(λa.λb.a) (λa.λb.b) (λa.λb.a)=(λb.(λa.λb.b)) (λa.λb.a)=λa.λb.b=false

Church numerals

Church numerals are the representations of natural numbers under Church encoding. The higher-order function that represents natural number n is a function that maps any function f to its n-fold composition. In simpler terms, a numeral represents the number by applying any given function that number of times in sequence, starting from any given starting value:

n:ffn
fn(x)=(fffn times)(x)=f(f((fn times(x))))

Church encoding is thus a unary encoding of natural numbers,[1] corresponding to simple counting. Each Church numeral achieves this by construction.

All Church numerals are functions that take two parameters. Church numerals 0, 1, 2, ..., are defined as follows in the lambda calculus:

Starting with 0 not applying the function at all, proceed with 1 applying the function once, 2 applying the function twice in a row, 3 applying the function three times in a row, etc.:
NumberFunction definitionLambda expression00 f x=x0=λf.λx.x11 f x=f x1=λf.λx.f x22 f x=f (f x)2=λf.λx.f (f x)33 f x=f (f (f x))3=λf.λx.f (f (f x))nn f x=fn xn=λf.λx.fn x

The Church numeral 3 is a chain of three applications of any given function in sequence, starting from some value. The supplied function is first applied to a supplied argument and then successively to its own result. The end result is not the number 3 (unless the supplied parameter happens to be 0 and the function is a successor function). The function itself, and not its end result, is the Church numeral 3. The Church numeral 3 means simply to do something three times. It is an ostensive demonstration of what is meant by "three times".

Calculation with Church numerals

Arithmetic operations on numbers produce numbers as their results. In Church encoding, these operations are represented by lambda abstractions which, when applied to Church numerals representing the operands, beta-reduce to the Church numerals representing the results.

Church representation of addition, plus(m,n)=m+n, uses the identity f(m+n)(x)=(fmfn)(x)=fm(fn(x)):

plusλmn.λfx.m f (n f x)

The successor operation, succ(n)=n+1, is obtained by β-reducing the expression "plus 1":

succλn.λfx.f (n f x)

Multiplication, mult(m,n)=m*n, uses the identity f(m*n)(x)=(fn)m(x):

multλmn.λfx.m (n f) x

Thus b (b f)(multb b) f and b (b (b f))(multb (multb b)) f, and so by the virtue of Church encoding expressing the n-fold composition, the exponentiation operation exp(b,n)=bn is given by

expλbn.n bλbnfx.n b f x

The predecessor operation pred(n) is a little bit more involved. We need to devise an operation that when repeated n+1 times will result in n applications of the given function f. This is achieved by using the identity function instead, one time only, and then switching back to f:

predλnfx.n (λri.i (r f)) (λf.x) I

As previously mentioned, I is the identity function, λx.x. See below for a detailed explanation. This suggests implementing e.g. halving and factorial in the similar fashion,

halfλnfx.n (λrab.a (r b a)) (λab.x) I ffactλnf.n (λra.a (r (succa))) (λa.f) 1

For example, pred4 f x beta-reduces to I(f (f (f x))), half 5 f x beta-reduces to I (f (I (f (I x)))), and fact4f beta-reduces to 1 (2 (3 (4 f))).

Subtraction, minus(m,n)=mn, is expressed by repeated application of the predecessor operation a given number of times, just like addition can be expressed by repeated application of the successor operation a given number of times, etc.:

minusλmn.npred mplusλmn.nsucc mmultλmn.n (mplus) 0expλmn.n (mmult) 1tetλn.n (λra.r a a) 0

tetn is the nth tetration operation, tet 3 a=0 a a a a=a a a, expressing a(aa). Similarly to the factorial definition above, it creates the "code" expression for it, and lets the Church numerals themselves do the rest.

Direct Subtraction and Division

Just as addition as repeated successor has its counterpart in the direct style, so can subtraction be expressed directly and more efficiently as well:

minusλmnfx.m (λrq.q r) (λq.x)(n (λqr.r q) (Y (λqr.f (r q))))

For example, minus 6 3 f x reduces to an equivalent of f (2 f x).

This also gives another predecessor version, beta-reducing λm.minus m 1 :

pred'λmfx.m (λrq.q r) (λq.x)(λr.r (Y (λqr.f (r q))))

Direct definition of division is given quite similarly as

divλmnfx.m (λrq.q r) (λq.x)(Y (λq.n (λqr.r q) (λr.f (r q)) (λx.x)))

The application to (λx.x) achieves subtraction by 1 while creating a cycle of actions repeatedly emitting an f after n1 steps.

Instead of Y, (λq.mqx) can also be used in each of the three definitions above.

Table of functions on Church numerals

Function Algebra Identity Function definition Lambda expressions
Successor n+1 f(n+1)=ffn succ n f x=f (n f x) λnfx.f (n f x) ...
Addition m+n f(m+n)=fmfn plus m n f x=m f (n f x) λmnfx.m f (n f x) λmn.nsuccm
Multiplication m*n f(m*n)=(fm)n multiply m n f x=m (n f) x λmnfx.m (n f) x λmnf.m (n f)
Exponentiation bn bn=(multb)n exp b n f x=n b f x λbnfx.n b f x λbn.n b
Predecessor[lower-alpha 1] n1 first((i,jj,fj)nI,I)=f(n1) pred(n+1) f x=I (n f x)

λnfx.n (λri.i (r f)) (λf.x) (λu.u)

Subtraction[lower-alpha 1] (Monus) mn mn=predn(m) minus m n=npredm ... λmn.npredm

Notes:

  1. 1.0 1.1 In the Church encoding,
    • pred(0)=0
    • mnmn=0

Predecessor function

The predecessor function is given as

predλnfx.n (λri.i (r f)) (λf.x) (λu.u)

This encoding essentially uses the identity

first( (i,jj,fj)nI,I )={Iif n=0,f(n1)otherwise

or

first( (x,yy,f(y))nx,x )={xif n=0,f(n1)(x)otherwise

An explanation of pred

The idea here is as follows. The only thing known to the Church numeral predn is the numeral n itself. Given two arguments f and x, as usual, the only thing it can do is to apply that numeral to the two arguments, somehow modified so that the n-long chain of applications thus created will have one (specifically, leftmost) f in the chain replaced by the identity function:

f(n1)(x)=I (f(f((fn1 timesn times(x)))))=(Xf)n(Zx) A=Xf (Xf ((Xfn times(Zx)))) A=X f r1 A1{ and it must be equal to: }=I (X f r2 A2)=I (f (X f r3 A3))=I (f (f (X f r4 A4)))=I (f (f (X f rn An)))=I (f (f (fn times (Z x An+1))))

Here Xf is the modified f, and Zx is the modified x. Since Xf itself can not be changed, its behavior can only be modified through an additional argument, A.

The goal is achieved, then, by passing that additional argument A along from the outside in, while modifying it as necessary, with the definitions

A1=IAi>1=fZ x f=x=K x fX f r Ai=Ai (r Ai+1){ i.e., }X f r i=i (r f)

Which is exactly what we have in the pred definition's lambda expression.

Now it is easy enough to see that

pred (succ n) f x=succ n (Xf) (K x) I=X f (n (X f) (K x)) I=I (n (Xf) (K x) f)= =I (f (f (f (K xf))))=I (n f x)=n f x 
pred 0 f x= 0 (Xf) (K x) I= K x I= x= 0 f x

i.e. by eta-contraction and then by induction, it holds that

pred (succ n)= npred 0= 0pred (pred 0)= pred 0 = 0

and so on.

Defining pred through pairs

The identity above may be coded with the explicit use of pairs. It can be done in several ways, for instance,

f= λp. pair (second p) (succ (second p))pred2= λn. first (n f (pair 0 0))

The expansion for pred23 is:

pred23= first (f (f (f (pair 0 0))))= first (f (f (pair 0 1)))= first (f (pair 1 2))= first (pair 2 3)= 2

This is a simpler definition to devise but leads to a more complex lambda expression,

pred2λn.n (λp.p (λabh.h b (succ b)))(λh.h 0 0)(λab.a)

Pairs in the lambda calculus are essentially just extra arguments, whether passing them inside out like here, or from the outside in as in the original pred definition. Another encoding follows the second variant of the predecessor identity directly,

pred3λnfx.n (λp.p (λabh.h b (f b)))(λh.h x x)(λab.a)

This way it is already quite close to the original, "outside-in" pred definition, also creating the chain of fs like it does, only in a bit more wasteful way still. But it is very much less wasteful than the previous, pred2 definition here. Indeed if we trace its execution we arrive at the new, even more streamlined, yet fully equivalent, definition

pred4λnfx.n (λrab.r b (f b))K x x

which makes it fully clear and apparent that this is all about just argument modification and passing. Its reduction proceeds as

pred43 f x= (..(..(..K))) x x= (..(..K))x (f x)= (..K)(f x) (f (f x))= K(f (f x)) (f (f (f x)))= f (f x)

clearly showing what is going on. Still, the original pred is much preferable since it's working in the top-down manner and is thus able to stop right away if the user-supplied function f is short-circuiting. The top-down approach is also used with other definitions like

pred5λnfx.n (λrab.a (r b b))(λab.x) I fthirdλnfx.n (λrabc.a (r b c a))(λabc.x) I I fthirdRoundedλnfx.n (λrabc.a (r b c a))(λabc.x) I f ItwoThirdsλnfx.n (λrabc.a (r b c a))(λabc.x) I f ffactorialλnfx.n (λra.a (r (succa)))(λa.f) 1 x

Division via General Recursion

Division of natural numbers may be implemented by,[2]

n/m=if nm then 1+(nm)/m else 0

Calculating nm with λnm.mpredn takes many beta reductions. Unless doing the reduction by hand, this doesn't matter that much, but it is preferable to not have to do this calculation twice (unless the direct subtraction definition is used, see above). The simplest predicate for testing numbers is IsZero so consider the condition.

IsZero (minus n m)

But this condition is equivalent to nm, not n<m. If this expression is used then the mathematical definition of division given above is translated into function on Church numerals as,

divide1 n m f x=(λd.IsZero d (0 f x) (f (divide1 d m f x))) (minus n m)

As desired, this definition has a single call to minus n m. However the result is that this formula gives the value of (n1)/m.

This problem may be corrected by adding 1 to n before calling divide. The definition of divide is then,

divide n=divide1 (succ n)

divide1 is a recursive definition. The Y combinator may be used to implement the recursion. Create a new function called div by;

  • In the left hand side divide1div c
  • In the right hand side divide1c

to get,

div=λc.λn.λm.λf.λx.(λd.IsZero d (0 f x) (f (c d m f x))) (minus n m)

Then,

divide=λn.divide1 (succ n)

where,

divide1=Y divsucc=λn.λf.λx.f (n f x)Y=λf.(λx.f (x x)) (λx.f (x x))0=λf.λx.xIsZero=λn.n (λx.false) true
trueλa.λb.afalseλa.λb.b
minus=λm.λn.npredmpred=λn.λf.λx.n (λg.λh.h (g f)) (λu.x) (λu.u)

Gives,

divide=λn.((λf.(λx.x x) (λx.f (x x))) (λc.λn.λm.λf.λx.(λd.(λn.n (λx.(λa.λb.b)) (λa.λb.a)) d ((λf.λx.x) f x) (f (c d m f x))) ((λm.λn.n(λn.λf.λx.n (λg.λh.h (g f)) (λu.x) (λu.u))m) n m))) ((λn.λf.λx.f (n f x)) n)

Or as text, using \ for λ,

divide = (\n.((\f.(\x.x x) (\x.f (x x))) (\c.\n.\m.\f.\x.(\d.(\n.n (\x.(\a.\b.b)) (\a.\b.a)) d ((\f.\x.x) f x) (f (c d m f x))) ((\m.\n.n (\n.\f.\x.n (\g.\h.h (g f)) (\u.x) (\u.u)) m) n m))) ((\n.\f.\x. f (n f x)) n))

For example, 9/3 is represented by

divide (\f.\x.f (f (f (f (f (f (f (f (f x))))))))) (\f.\x.f (f (f x)))

Using a lambda calculus calculator, the above expression reduces to 3, using normal order.

\f.\x.f (f (f (x)))

Predicates

A predicate is a function that returns a Boolean value. The most fundamental predicate on Church numerals is IsZero, which returns true if its argument is the Church numeral 0, and false otherwise:

IsZero=λn.n (λx.false) true

The following predicate tests whether the first argument is less-than-or-equal-to the second:

LEQ=λm.λn.IsZero (minus m n)

Because of the identity

x=y(xyyx)

the test for equality can be implemented as

EQ=λm.λn.and (LEQ m n) (LEQ n m)

In programming languages

Most real-world languages have support for machine-native integers; the church and unchurch functions convert between nonnegative integers and their corresponding Church numerals. The functions are given here in Haskell, where the \ corresponds to the λ of Lambda calculus. Implementations in other languages are similar.

type Church a = (a -> a) -> a -> a

church :: Integer -> Church Integer
church 0 = \f -> \x -> x
church n = \f -> \x -> f (church (n-1) f x)

unchurch :: Church Integer -> Integer
unchurch cn = cn (+ 1) 0

Signed numbers

One simple approach for extending Church Numerals to signed numbers is to use a Church pair, containing Church numerals representing a positive and a negative value.[3] The integer value is the difference between the two Church numerals.

A natural number is converted to a signed number by,

converts=λx.pair x 0

Negation is performed by swapping the values.

negs=λx.pair (second x) (first x)

The integer value is more naturally represented if one of the pair is zero. The OneZero function achieves this condition,

OneZero=λx.IsZero (first x) x (IsZero (second x) x (OneZero (pair (pred (first x)) (pred (second x)))))

The recursion may be implemented using the Y combinator,

OneZ=λc.λx.IsZero (first x) x (IsZero (second x) x (c (pair (pred (first x)) (pred (second x)))))
OneZero=YOneZ

Plus and minus

Addition is defined mathematically on the pair by,

x+y=[xp,xn]+[yp,yn]=xpxn+ypyn=(xp+yp)(xn+yn)=[xp+yp,xn+yn]

The last expression is translated into lambda calculus as,

pluss=λx.λy.OneZero (pair (plus (first x) (first y)) (plus (second x) (second y)))

Similarly subtraction is defined,

xy=[xp,xn][yp,yn]=xpxnyp+yn=(xp+yn)(xn+yp)=[xp+yn,xn+yp]

giving,

minuss=λx.λy.OneZero (pair (plus (first x) (second y)) (plus (second x) (first y)))

Multiply and divide

Multiplication may be defined by,

x*y=[xp,xn]*[yp,yn]=(xpxn)*(ypyn)=(xp*yp+xn*yn)(xp*yn+xn*yp)=[xp*yp+xn*yn,xp*yn+xn*yp]

The last expression is translated into lambda calculus as,

mults=λx.λy.pair (plus (mult (first x) (first y)) (mult (second x) (second y))) (plus (mult (first x) (second y)) (mult (second x) (first y)))

A similar definition is given here for division, except in this definition, one value in each pair must be zero (see OneZero above). The divZ function allows us to ignore the value that has a zero component.

divZ=λx.λy.IsZero y 0 (divide x y)

divZ is then used in the following formula, which is the same as for multiplication, but with mult replaced by divZ.

divides=λx.λy.pair (plus (divZ (first x) (first y)) (divZ (second x) (second y))) (plus (divZ (first x) (second y)) (divZ (second x) (first y)))

Rational and real numbers

Rational and computable real numbers may also be encoded in lambda calculus. Rational numbers may be encoded as a pair of signed numbers. Computable real numbers may be encoded by a limiting process that guarantees that the difference from the real value differs by a number which may be made as small as we need.[4] [5] The references given describe software that could, in theory, be translated into lambda calculus. Once real numbers are defined, complex numbers are naturally encoded as a pair of real numbers.

The data types and functions described above demonstrate that any data type or calculation may be encoded in lambda calculus. This is the Church–Turing thesis.

List encodings

A list contains some items in order. The basic operations on lists are:

Function Description
nil Construct an empty list
isnil Test if list is empty
cons Prepend a given value to a (possibly empty) list
head Get the first element of the list
tail Get the rest of the list
singleton Create a list containing one given element
append Append two lists together
fold Fold the list with the given "plus" and "zero"

A representation of lists should provide ways to implement these operations.

The archetypal lambda calculus representation of lists is Church List encoding. It represents lists as right folds, as functions to return the results of folding over the list with user-supplied arguments.

It follows the paradigm of "a thing is the result of its observation". No matter the concrete implementation, folding a given list of values results in the same result. This provides an abstract view at what a list is. Church List encoding is such a mechanism.

On the other hand, seen more concretely, lists can be represented as a sequence of linked list nodes.

What follows are four different representations of lists:

  • Church lists – right fold representation.
  • Two Church pairs for each list node.
  • One Church pair for each list node.
  • Scott encoding.

Church lists – right fold representation

This is the original Church encoding for lists. A list is represented by a binary function, that, when supplied with two arguments, – a "combining function" and a "sentinel value", – will perform the right fold of the encoded list using those two arguments.

For an empty list the sentinel value is returned as the folding's result. The result of folding a non-empty list with head h and tail t is the result of combining, by the supplied function, of the head h with the result of folding the tail t with the supplied two arguments. Thus the combining function's two arguments are, conceptually, the current element and the result of folding the rest of the list.

For example, a list of three elements x, y and z is represented by a term that when applied to c and n returns c x (c y (c z n)). Equivalently, it is an application of the chain of functional compositions ( ) of partial applications, ((c x) (c y) (c z)) n.

nilλcn.nisnilλl.l (λhr.false) trueconsλht.λcn.c h (t c n)singletonλh.λcn.c h nappendλlt.λcn.l c (t c n)nonemptyλl.l (λhr.true) falseheadλl.l (λhr.h) falsesafeHeadλles.l (λhr.s h) efoldλcnl.l c nmapλfl.λcn.l (λhr.c (f h) r) nλflc.l (cf)tailλl.λcn.l (λhrg.g h (r c)) (λg.n) (λht.t)

These definitions follow the following logic: the equations

 fold c n [  ]     =  n
 fold c n [x ]     =  c x n
 fold c n [x,y,z]  =  c x (c y (c z n))

mean that

{ [    ] }λcn.n{ [ x   ] }λcn.c x n{ [ x,y,z ] }λcn.c x (c y (c z n))

where { l }=λcn.fold c n l denotes the Church List representation of the list l.

Since Church encoded list is its own folding function, folding it just means applying that function to the supplied arguments.

This list representation can be given type in System F.

The evident correspondence to Church numerals is non-coincidental, as that can be seen as a unary encoding, with natural numbers represented by lists of unit (i.e. non-important) values, e.g. [() () ()], with the list's length serving as the representation of the natural number. Right folding over such lists uses functions which necessarily ignore the element's value, and is equivalent to the chained functional composition, i.e. ( (c ()) (c ()) (c ()) ) n = (f f f) n, as is used in Church numerals.

Two pairs as a list node

A nonempty list can be represented by a Church pair, where

  • First contains the list's head
  • Second contains the list's tail

However this does not give a representation of the empty list, because there is no "null" pointer. To represent null, the pair can be wrapped in another pair, giving three values:

  • First - the null list indicator (a Boolean).
  • Second.First contains the head (car).
  • Second.Second contains the tail (cdr).

Using this idea the basic list operations can be defined like this:[6]

Expression Description
nilpair true true The first element of the pair is true meaning the list is null.
isnilfirst Retrieve the null (or empty list) indicator.
consλh.λt.pairfalse (pairh t) Create a list node, which is not null, and give it a head h and a tail t.
headλz.first (secondz) second.first is the head.
tailλz.second (secondz) second.second is the tail.

In a nil node second is never accessed, provided that head and tail are only applied to nonempty lists.

One pair as a list node

Alternatively, define[7]

conspairheadλl. l (λhtd. h) niltailλl. l (λhtd. t) nilnilfalseisnilλl.l (λhtd.false)true

where the definitions like the last one all follow the same general pattern for the safe use of a list, with h and t referring to the list's head and tail, and d being discarded, as an artificial device:

λl.l (λhtd.head-and-tail-clause) nil-clause

Other operations in this encoding are:

lfoldλf. Y (λr.λal. l (λhtd. r (f a h) t) a)rfoldλfa. Y (λr.λl. l (λhtd. f (r t) h) a)lengthlfold (λah. succ a) zero

mapλf. rfold (λah. cons (f h) a) nilfilterλp. rfold (λah. p h (cons h a) a) nilreversefold (λah. cons h a) nilconcatλlg. rfold (λah. cons h a) g lconjλlv. concat l (cons v nil)

dropλn. n tailY (λr.λnl. l (λhtd. IsZero n l (r (pred n) t)) nil)drop-lastλnl. IsZero n l second(        Y (λrlr. lr (λhtd.            r t (λnala. IsZero na                    (pair zero (cons h la))                    (pair (pred na) nil) ))            (pair n nil) )         l )drop-whileλp. Y (λrl. l (λhtd. p h (r t) l) nil)takeY (λrnl. l (λhtd. IsZero n nil (cons h (r (pred n) t))) nil)take-lastλnl. IsZero n l second(        Y (λrlr. lr (λhtd.            r t (λnala. IsZero na                    (pair zero la)                    (pair (pred na) lr) ))            (pair n nil) )         l)take-whileλp. Y (λrl. l (λhtd. p h (cons h (r t)) nil) nil)

allY (λrpl. l (λhtd. p h (r p t) false) true)anyY (λrpl. l (λhtd. p h true (r p t)) false)element-atλnl. head (drop n l)insert-atλnvl. concat (take n l) (cons v (drop n l))remove-atλnl. concat (take n l) (drop (succ n) l)replace-atλnvl. concat (take n l) (cons v (drop (succ n) l))index-ofλp. Y (λrnl. l (λhtd. p h n (r (succ n) t)) zero) onelast-index-ofλp. Y (λrnl. l (λhtd. (λi. IsZero i (p h n zero) i) (r (succ n) t)) zero) onerangeλfz. Y (λrsn. IsZero n nil (cons (s f z) (r (succ s) (pred n)))) zerorepeatλv. Y (λrn. IsZero n nil (cons v (r (pred n))))zipY (λrl1l2. l1 (λh1t1d1. l2 (λh2t2d2. cons (pair h1 h2) (r t1 t2)) nil) nil)

Scott lists

Scott encoding for data types follows their surface syntax without regard to recursion. In the disjunction of conjunctions a.k.a. sum of products style of data type definitions, it represents a datum as a function which expects as many arguments as there are alternatives in its data type definition, where each such argument is expected to be a "handler" function that must be able to handle a given number of data arguments that will correspond to the data fields for that alternative.

For lists, it means the data type definition of

List:=NIL |ConsvalList

and lists being represented as

NIL=λnc.nCons=λad.λnc.c a dIsEmpty=λl.ltrue(λad.false)Head=λl.lNIL(λad.a)Tail=λl.lNIL(λad.d)fold=λgz.Yλrl.l z (λad.ga (r d))Append=foldConsMap=λf.fold(λh.Cons(fh))NILMap2=λf.Yλrpq.pNIL(λad.                 qNIL(λbg.Cons(fab)(r d g)))

Recursive operations on Scott lists typically require explicit use of recursion, e.g. using Y combinator, or explicit self-application definitions. One such example is fold, unlike the no-op that it is under Church encoding. But tail is immediately available, so its definition is much simpler here, in comparison. See Scott encoding for more.

Scott encoding can be seen as using the idea of continuations, which can lead to simpler code[8]. In this approach, we use the fact that lists can be observed using pattern matching expression. For example, using Scala notation, if list denotes a value of type List with empty list Nil and constructor Cons(h, t) we can inspect the list and compute nilCode in case the list is empty and consCode(h, t) when the list is not empty:

list match {
  case Nil        => nilCode
  case Cons(h, t) => consCode(h,t)
}

The list is given by how it acts upon nilCode and consCode. We therefore define a list as a function that accepts such nilCode and consCode as arguments, so that instead of the above pattern match we may simply write:

list nilCode consCode

Let us denote by n the parameter corresponding to nilCode and by c the parameter corresponding to consCode. The empty list is the one that returns the nil argument:

nilλn.λc. n

The non-empty list with head h and tail t is given by

cons h t    λn.λc. c h t

More generally, an algebraic data type with m alternatives becomes a function with m parameters. When the ith constructor has ni arguments, the corresponding parameter of the encoding takes ni arguments as well.

Scott encoding can be done in untyped lambda calculus, whereas its use with types requires a type system with recursion and type polymorphism. A list with element type E in this representation that is used to compute values of type C would have the following recursive type definition, where '=>' denotes function type:

type List = 
  C =>                    // nil argument
  (E => List => C) =>     // cons argument
  C                       // result of pattern matching

A list that can be used to compute arbitrary types would have a type that quantifies over C. A list generic [clarification needed] in E would also take E as the type argument.

General Remarks

A straightforward implementation of Church encoding slows some access operations from O(1) to O(n), where n is the size of the data structure, making Church encoding impractical.[9] Research has shown that this can be addressed by targeted optimizations, but most functional programming languages instead expand their intermediate representations to contain algebraic data types.[10] Nonetheless Church encoding is often used in theoretical arguments, as it is a natural representation for partial evaluation and theorem proving.[9] Operations can be typed using higher-ranked types,[11] and primitive recursion is easily accessible.[9] The assumption that functions are the only primitive data types streamlines many proofs.

Church encoding is complete but only representationally. Additional functions are needed to translate the representation into common data types, for display to people. It is not possible in general to decide if two functions are extensionally equal due to the undecidability of equivalence from Church's theorem. The translation may apply the function in some way to retrieve the value it represents, or look up its value as a literal lambda term. Lambda calculus is usually interpreted as using intensional equality. There are potential problems with the interpretation of results because of the difference between the intensional and extensional definition of equality.

See also

References

  1. Jansen, Jan Martin (2013), "Programming in the λ-calculus: from Church to Scott and back", The Beauty of Functional Code, Lecture Notes in Computer Science, 8106, Springer-Verlag, pp. 168–180, doi:10.1007/978-3-642-40355-2_12, ISBN 978-3-642-40354-5 .
  2. Allison, Lloyd. "Lambda Calculus Integers". http://www.csse.monash.edu.au/~lloyd/tildeFP/Lambda/Examples/const-int/. 
  3. Bauer, Andrej. "Andrej's answer to a question; "Representing negative and complex numbers using lambda calculus"". https://cs.stackexchange.com/q/2272. 
  4. "Exact real arithmetic". https://wiki.haskell.org/Exact_real_arithmetic. 
  5. Bauer, Andrej (26 September 2022). "Real number computational software". https://github.com/andrejbauer/marshall. 
  6. Pierce, Benjamin C. (2002). Types and Programming Languages. MIT Press. pp. 500. ISBN 978-0-262-16209-8. 
  7. Tromp, John (2007). "14. Binary Lambda Calculus and Combinatory Logic". in Calude, Cristian S. Randomness And Complexity, From Leibniz To Chaitin. World Scientific. pp. 237–262. ISBN 978-981-4474-39-9. https://books.google.com/books?id=flPICgAAQBAJ&pg=PP1. 
    As PDF: Tromp, John (14 May 2014). "Binary Lambda Calculus and Combinatory Logic". https://tromp.github.io/cl/LC.pdf. 
  8. Jansen, Jan Martin (2013). "Programming in the λ-Calculus: From Church to Scott and Back". in Achten, Peter; Koopman, Pieter W. M.. The Beauty of Functional Code - Essays Dedicated to Rinus Plasmeijer on the Occasion of His 61st Birthday. Lecture Notes in Computer Science. 8106. Springer. pp. 168–180. doi:10.1007/978-3-642-40355-2_12. ISBN 978-3-642-40354-5. 
  9. 9.0 9.1 9.2 Trancón y Widemann, Baltasar; Parnas, David Lorge (2008). "Implementation and Application of Functional Languages". 19th International Workshop, IFL 2007, Freiburg, Germany, September 27–29, 2007 Revised Selected Papers. 5083. pp. 228–229. doi:10.1007/978-3-540-85373-2_13. ISBN 978-3-540-85372-5. https://books.google.com/books?id=E1zuY1Q6sOsC&pg=PA228. 
  10. Jansen, Jan Martin; Koopman, Pieter W. M.; Plasmeijer, Marinus J. (2006). "Efficient interpretation by transforming data types and patterns to functions". in Nilsson, Henrik. Trends in functional programming. Volume 7. Bristol: Intellect. pp. 73–90. ISBN 978-1-84150-188-8. 
  11. "Predecessor and lists are not representable in simply typed lambda calculus". Lambda Calculus and Lambda Calculators. okmij.org. https://okmij.org/ftp/Computation/lambda-calc.html#predecessor. 
  • Stump, A. (2009). "Directly reflective meta-programming". High-Order Symb Comput 22 (2): 115–144. doi:10.1007/s10990-007-9022-0. http://www.cs.uiowa.edu/~astump/papers/archon.pdf. 
  • Cartwright, Robert. "Church numerals and booleans explained". Comp 311 — Review 2. Rice University. http://www.cs.rice.edu/~javaplt/311/Readings/supplemental.pdf. 
  • Kemp, Colin (2007). "§2.4.1 Church Naturals, §2.4.2 Church Booleans, Ch. 5 Derivation techniques for TFP". Theoretical Foundations for Practical 'Totally Functional Programming' (PhD). School of Information Technology and Electrical Engineering, The University of Queensland. pp. 14–17, 93–145. CiteSeerX 10.1.1.149.3505. All about Church and other similar encodings, including how to derive them and operations on them, from first principles
  • Some interactive examples of Church numerals
  • Lambda Calculus Live Tutorial: Boolean Algebra

Template:Alonzo Church