Lambda Calculus and Lambda Calculators

Lambda-calculators


 

Negative numbers, subtraction and division in lambda-calculus

This article will demonstrate basic arithmetic operations -- comparison, addition, subtraction, multiplication, and division -- on non-negative and negative integer numbers. Both the integers and the operations on them are represented as terms in the pure untyped lambda-calculus. The only building blocks are identifiers, abstractions and applications. No constants or delta-rules are used. Reductions follow only the familiar beta-substitution and eta-rules. We also show two approaches of defining a predecessor of a Church numeral. Curiously, none of the arithmetic operations involve the Y combinator; even the division gets by without Y.

Addition, multiplication, squaring, and exponentiation are easily expressed in lambda-calculus. We discuss two approaches to their "opposites" -- subtraction, division, finding of a square root and of a discrete logarithm. The "opposite" operations present quite a challenge. One approach, based on fixpoints, is more elegant but rather impractical. The "dual" approach, which relies on counting, leads to constructive and useful, albeit messy, terms.

Version
The current version is 1.2, Jul 14, 2002.
References

lambda-calc-div-neg.txt [plain text file]
The article itself. It was originally posted as Negativism and division in lambda-calculus on the newsgroup comp.lang.functional on Sun, 13 May 2001 23:12:25 GMT

lambda-arithm-neg.scm [14K]
Negative numbers and four arithmetic operations on integers
The source code that defines and tests all four operations of arithmetics on positive and negative integers, in lambda-calculus. The code is meant to be evaluated by a practical lambda-calculator in Scheme.

LC_neg.lhs [17K]
Negative numbers and four arithmetic operations on integers [Haskell version]
This is a literate Haskell code that defines and tests all four operations of arithmetics on positive and negative integers, in lambda-calculus. The code is meant to be evaluated by a practical lambda-calculator in Haskell.

lambda-calc-opposites.txt [plain text file]
An article Subtraction, division, logarithms and other opposites in Lambda calculus posted on comp.lang.functional on Tue, 29 May 2001 20:58:02 -0700

lambda-arithm-div-term.scm [8K]
Lambda abstraction term for division
An unadorned lambda term that implements division of two signed integers (also represented as lambda terms). The article explains in detail how this division term has been derived.

 

Basic Lambda Calculus terms

Definitions of basic lambda terms: Church numerals, combinators, Booleans, etc. These are basic lambda-calculus terms, needed to run more advanced examples. Two versions of the terms are given, in the notation of the Scheme and Haskell calculators.

Version
The current version is 1.3, Aug 18, 2002.
References

lambda-arithm-basic.scm [4K]
A version for the Scheme calculator.

LC_basic.lhs [4K]
A version for the Haskell calculator. This is a literate Haskell code that defines the terms and shows examples of their use.

 

Numerals and lists in lambda-calculus: P-numerals

This article derives a term in the pure untyped lambda-calculus that efficiently computes a symmetric difference of two Church numerals. We introduce other numerals, so called P-numerals, which are more convenient for arithmetics. We show the connection between the P-numerals and the list fold.

P-numerals are the functional equivalent of lists: increment, decrement, and zero testing operations on P-numerals all take constant time -- just as cons, car, and null? do on lists.

Peter G. Hancock has observed that P-numerals are closely related to Goedel's recursor R.

Andrew Hodges, in `Alan Turing: The Enigma', wrote: ``But underneath there lay the same powerful idea that Goedel has used, that there was no essential distinction between numbers and operations on numbers.'' And so, lambda-calculus and Turing machine are duals: In a (universal) TM, an integer encodes an operation. In lambda-calculus, an operation encodes an integer.

Version
The current version is 1.3, Dec 31, 2005.
References

LC_Pnum.lhs [11K]
The article itself. This is also a complete, literate Haskell code that defines the numerals and the symmetric difference, gives an example of their use, and compares Church and P-numerals.
The article was originally posted as Symmetric difference in LC, P-numerals, and fold on comp.lang.functional on Fri Aug 30 01:49:31 2002

Peter G. Hancock: The AMEN combinators and their reduction.
Combinatorially complete arithmetic operations, and a rewriting calculus for arithmetical expressions built entirely upon addition, multiplication, exponentiation, and naught.
<http://homepages.inf.ed.ac.uk/v1phanc1/arithmetic.lhs>

 

The bluff combinator

A Bluff combinator problem in the pure untyped lambda-calculus was posed by Mayer Goldberg in the 1990s:

Let c_i denote a Church numeral for the number i. We should design two terms beq and bluff so that the following reductions hold:

     beq c_i c_j     ==> \x\y.x (that is, boolean 'true')
                         iff i == j
                     ==> \x\y.y (that is, boolean 'false') otherwise
     
     beq bluff c_i   ==> \x\y.x (that is, boolean 'true') for all i
     beq c_i bluff   ==> \x\y.x (that is, boolean 'true') for all i
     beq bluff bluff ==> \x\y.y (that is, boolean 'false')

In other words, beq should act as equality on Church numerals. The bluff combinator should be beq-equal to any numeral. However, the combinator should not be bequal to itself. The gist of the problem is discriminating a Church numeral from some other term.

Version
The current version is 1.2, Oct 14, 2002.
References

bluff.lhs [6K]
The complete code that shows one solution to the problem. Other solutions are described in an article below.

Mayer Goldberg and Mads Torgersen: Circumventing Church Numerals. Nordic Journal of Computing, v9, January 2002, pp. 1-12.

 

Miscellaneous curious equalities of particular lambda-terms

This section collects curious properties of particular lambda-terms. Some of the properties have been used in proving theorems or solving puzzles described on this site. Throughout this section, c_i means a Church numeral for integer i, true stands for a term \x\y.x and false stands for \x\y.y . The symbol ==> indicates reduction in one or several steps.

c_i (\x.false) false ==> false
This property of Church numerals helped to solve the bluff combinator problem.
 
c_i combI ==> combI
where combI is the identity combinator \x.x. Thus the identity combinator is a fixpoint of any Church numeral.
 
c_i c_j c_k ==> c_n where n=k^(j^i)
and the operator ^ means exponentiation. The property says that an application of a Church numeral to two other Church numerals is itself a Church numeral, which corresponds to exponentiated integers.
 
c_1 === combI,  true === K,  c_0 === false
Trivial statements that c_1 is the identity combinator and true is the K (a.k.a. const) combinator. In Lambda calculus -- as in C, Perl and other programming languages -- numeral 0 and boolean false are the same.
 
c_i (\y.x) u ==> x, c_0 (\y.x) u ==> u, i>0
This property gives a simple test for discriminating c_0 from any other Church numeral.
 
cons a x (cons b y) ==> a b y x
where cons is \x\y\p.p x y.
 
Version
The current version is 1.2, Dec 24, 2002.
 

switch in lambda-calculus

We implement the switch combinator, a lambda-term with the following reduction rules:

     switch 0 -> id
     switch n test1 stmt1 test2 stmt2 ... test_n stmt_n default
       -> stmt_i    for the first i such that test_i -> true
       -> default   otherwise
Here n is a Church numeral, test_i are Church Booleans, stmt_i and default are arbitrary terms. We impose an additional constraint of avoiding general recursion.

For example, assuming c2 stands for Church numeral 2, etc., and true, false, and zerop are combinators with the obvious meaning,

     ((switch c2) true  x true y z)              ; reduces to: x
     ((switch c2) false x true y z)              ; reduces to: y
     ((switch c3) false x false y (zerop c1) z h ; reduces to: h
Version
The current version is 1.1, Mar 25, 2003.
References
LC_switch.lhs [4K]
The complete code with the explanation and examples
The code was first posted in a message Re: Lambda Calculus Question on a newsgroup comp.lang.functional on Tue, 25 Mar 2003 14:13:34 -0800
 

Predecessor and lists are not representable in simply typed lambda-calculus

The predecessor of a Church-encoded numeral, or, generally, the encoding of a list with the car and cdr operations are both impossible in the simply typed lambda-calculus. Henk Barendregt's ``The impact of the lambda-calculus in logic and computer science'' (The Bulletin of Symbolic Logic, v3, N2, June 1997) has the following phrase, on p. 186:

Even for a function as simple as the predecessor lambda definability remained an open problem for a while. From our present knowledge it is tempting to explain this as follows. Although the lambda calculus was conceived as an untyped theory, typeable terms are more intuitive. Now the functions addition and multiplication are defineable by typeable terms, while [101] and [108] have characterized the lambda-defineable functions in the (simply) typed lambda calculus and the predecessor is not among them [the story of the removal of Kleene's four wisdom teeth is skipped...]
Ref 108 is R.Statman: The typed lambda calculus is not elementary recursive. Theoretical Comp. Sci., vol 9 (1979), pp. 73-81.
Since list is a generalization of numeral -- with cons being a successor, append being the addition, tail (aka cdr) being the predecessor -- it follows then the list cannot be encoded in the simply typed lambda-calculus.

To encode both operations, we need either inductive (generally, recursive) types, or System F with its polymorphism. The first approach is the most common. Indeed, the familiar definition of a list

     data List a = Nil | Cons a (List a)
gives an (iso-) recursive data type (in Haskell. In ML, it is an inductive data type).

Lists can also be represented in System F. As a matter of fact, we do not need the full System F (where the type reconstruction is not decidable). We merely need the extension of the Hindley-Milner system with higher-ranked types, which requires a modicum of type annotations and yet is able to infer the types of all other terms. This extension is supported in Haskell and OCaml. With such an extension, we can represent a list by its fold, as shown in the code below. It is less known that this representation is faithful: we can implement all list operations, including tail, drop, and even zip.

References

How to zip folds: A library of fold transformers (streams)

Detailed discussion of various representations of lists in Haskell, and their typing issues [plain text file]

The message was originally posted as Re: Lists vs. Monads on Haskell-Cafe mailing list on Thu, 21 Jul 2005 19:30:38 -0700 (PDT)


 

A practical Lambda-calculator in Scheme

The code below implements a normal-order interpreter for the untyped lambda-calculus. The interpret permits "shortcuts" of terms. The shortcuts are not first class and do not alter the semantics of the lambda-calculus. Yet they make complex terms easier to define and apply.

The code also includes a few convenience tools: tracing of all reduction, comparing two terms modulo alpha-renaming, etc.

Version
The current version is 1.1, Mar 30, 2001.
References

A practical lambda-calculator in Scheme

Basic Lambda Calculus terms

 

Lambda-calculator as a CPS R5RS macro

Another normal-order interpreter for untyped lambda-calculus, implemented as a syntax-rule macro. The source and the object languages of the calculator are regular Scheme terms. Lambda-abstractions for the calculator are ordinary lambda-forms of Scheme:

     (?lc-calc
      ((lambda (x) (x x)) (lambda (y) (y z))) ; term to reduce
      (??!lambda (result) (display '(??! result)))
     )
expands to (display '(z z)). The funny ??!lambda is a macro-lambda -- the abstraction of the (meta-) calculator.

The calculator normalizes regular Scheme terms. The result can be compiled and evaluated in a call-by-value lambda-calculus with constants (i.e., Scheme). The lambda-calculator acts therefore as a partial evaluator.

Version
The current version is Dec 16, 2001.
References
Lambda-calculator as a R5RS macro
 

Lambda-calculator as a short, direct-style R5RS macro

Yet another normal-order interpreter for untyped lambda-calculus, implemented as a direct-style syntax-rule macro. This implementation is the shortest and the fastest one. It does no alpha-renaming directly and no substitutions directly. Everything is integrated with normalization, and everything is delayed until the latest possible moment. The source and the object languages of the calculator are regular Scheme terms. Lambda-abstractions for the calculator are ordinary lambda-forms of Scheme:

     (((NORM ((lambda (c)     ; succ
                  (lambda (f) (lambda (x) (f ((c f) x)))))
              (lambda (f) f)  ; c1
             ))
       (lambda (u) (+ 1 u))) 0)
normalizes the application of the succ lambda-term to c1, Church numeral 1. The result, which is a Scheme procedure, is then applied to Scheme values (lambda (u) (+ 1 u)) and 0 to yield 2 -- which shows that the result of the normalization was Church numeral 2.

The calculator normalizes regular Scheme terms. The result can be compiled and evaluated in a call-by-value lambda-calculus with constants (i.e., Scheme). The lambda-calculator acts therefore as a partial evaluator.

Version
The current version is December 2004.
References
Lambda-calculator as a R5RS macro
 

A practical Lambda-calculator in Haskell

The present calculator implements what seems to be an efficient and elegant algorithm of normal order reductions. The algorithm is "more functional" than the traditionally used approach. The algorithm seems identical to that employed by yacc sans one critical difference. The calculator also takes a more "functional" approach to the hygiene of beta-substitutions, which is achieved by coloring of identifiers where absolutely necessary. This approach is "more functional" because it avoids a global counter or the threading of the paint bucket through the whole the process. The integration of the calculator with Haskell lets us store terms in variables and easily and intuitively combine them.

The traditional recipe for normal-order reductions includes an unpleasant phrase "cook until done". The phrase makes it necessary to keep track of reduction attempts, and implies an ugly iterative algorithm. We're proposing what seems to be an efficient and elegant technique that can be implemented through intuitive re-writing rules. Our calculator, like yacc, possesses a stack and works by doing a sequence of shift and reduce steps. The only significant difference from yacc is that the lambda-calculator "reparses" the result after the successful reduce step. The source and the target languages of our "parser" (lambda-calculator) are the same; therefore, the parser can indeed apply itself.

The parsing stack can be made implicit. In that case, the algorithm can be used for normalization of typed lambda-terms in Twelf.

The following examples show that lambda-calculus becomes a domain-specific language embedded into Haskell:

     > c0 = f ^ x ^ x                -- Church numeral 0
     > succ = c ^ f ^ x ^ f # (c # f # x)            -- Successor
     
     > c1 = eval $ succ # c0   -- pre-evaluate other numerals
     > c2 = eval $ succ # c1
     > c3 = eval $ succ # c2
     > c4 = eval $ succ # c3

It is indeed convenient to store terms in Haskell variables and pre-evaluate (i.e., normalize) them. They are indeed terms. We can always ask the interpreter to show the term. For example, show c4 yields (\f. (\x. f (f (f (f x))))).

     let mul = a ^ b ^ f ^ a # (b # f)                 -- multiplication
     eval $ mul # c1 ---> (\b. b), the identity function
     eval $ mul # c0 ---> (\b. (\f. (\x. x))), which is "const 0"

These are algebraic results: multiplying any number by zero always gives zero. We can see now how lambda-calculus can be useful for theorem proving, even over universally-quantified formulas.

The calculator implements Dr. Fairbairn's suggestion to limit the depth of printed terms. This makes it possible to evaluate and print some divergent terms (so-called tail-divergent terms):

     Lambda_calc> let y_comb = f^((p^p#p) # (c ^ f#(c#c))) in eval $ y_comb#c
     c (c (c (c (c (c (c (c (c (c (...)))))))))) 
It is amazing how well lambda-calculus and Haskell play together.

A monadic version of the calculator gives us the trace of the reduction steps.

Version
The current version is 2.3, May 5, 2005.
References

Lambda_calc.lhs [23K]
The complete literate Haskell code for the calculator.
The code also includes convenience functions to list free variables of a term and to compare two terms modulo alpha-renaming. The latter function is extensively used in built-in regression tests. To run the tests, evaluate all_tests.
The code was first posted in a message ANN: Normal-order evaluation as bottom-up parsing on Sun, 28 Apr 2002 14:11:59 -0700 on the Haskell mailing list.

Basic Lambda Calculus terms

Reynald Affeldt. Abstract machines for functional languages. A Survey.
<http://web.yl.is.s.u-tokyo.ac.jp/~affeldt/study/abstract_machines.ps>
The survey describes SECD, Krivine, CAM and ZAM machines and several of their variations.
Incidentally, Lambda_calc.lhs appears to have little in common with Krivine, SECD or other machines. The Lambda_calc.lhs machine has stack, but it has no concept of environment. This is indicative of a larger difference: in Lambda_calc.lhs variables have 'no meaning'. To this machine, normalization of lambda terms is a pure syntactic transformation, akin to a transformation of (((a+b))) into a+b by a regular parser.

 

Type-level call-by-value lambda-calculator in three lines

We present a type-level implementation of the call-by-value lambda-calculus with booleans, natural numbers, and case discrimination. The terms of our (untyped) calculus are Haskell types; the calculator transforms Haskell types and is, essentially, a type function (a type class constraint, to be precise).

The implementation of lambda-calculus reductions takes only three lines of code:

     instance                                   E (F x)           (F x)
     instance (E y y', A (F x) y' r)         => E ((F x) :< y)    r
     instance (E (x :< y) r', E (r' :< z) r) => E ((x :< y) :< z) r
The first line says that abstractions evaluate to themselves, the second line executes the redex, and the third recurses to find it. The examples in the source code demonstrate partial applications, the fixpoint combinator, the Fibonacci function, and S and K combinators. Incidentally, the realization of the S combinator again takes three lines, two of which build the closures (partial applications) and the third executing the familiar S-rule:
     instance A (F CombS)     f (F (CombS,f))
     instance A (F (CombS,f)) g (F (CombS,f,g))
     instance E (f :< x :< (g :< x)) r => A (F (CombS,f,g)) x r
The encoding of the applicative fixpoint combinator is even simpler:
     data Rec l
     instance E (l :< (F (Rec l)) :< x) r => A (F (Rec l)) x r
expressing the reduction of the application (fix l) x to l (fix l) x. Incidentally, the present code constitutes what seems to be the shortest proof that the type system of Haskell with the undecidable instances extension is indeed Turing-complete.

The distinct feature of our implementation, besides its simplicity, is the primary role of application rather than abstraction. Yet we trivially represent closures and higher-order functions. We use proper names for function arguments (rather than deBruijn indices), and yet we avoid the need for fresh name generation, name comparison, and alpha-conversion. We have no explicit environment and no need to propagate and search it, and yet we can partially apply functions. We represented closures in a converted form, as first-order type structures.

Our implementation fundamentally relies on the connection between polymorphism and abstraction, taking the full advantage of the type-lambda implicitly present in Haskell. The reason for the triviality of our code is the type checker's already doing most of the work need for an implementation of lambda-calculus.

Version
The current version is 1.1, Sep 14, 2006.
References

TypeLC.lhs [9K]
The complete literate Haskell code with explanations and tests, including Fibonacci, S and K combinators and the combinatorial arithmetic
The code was originally posted in a message On computable types. I. Typed lambda and type closures on Thu, 14 Sep 2006 19:07:29 -0700 (PDT) on the Haskell mailing list.

Applications of computable types



Last updated January 1, 2009

This site's top page is http://okmij.org/ftp/

oleg-at-pobox.com or oleg-at-okmij.org
Your comments, problem reports, questions are very welcome!

Converted from SXML by SXML->HTML