1.5. The Untyped Lambda Calculus

The lambda calculus was proposed by Alonzo Church in the 1930s as a formal model of computation. Its most striking feature is its economy: the whole language is built from just three concepts — variables, abstraction (defining functions) and application (calling functions). Despite this extreme simplicity, the lambda calculus is Turing-complete: every computable function can be represented in it.

The lambda calculus is the theoretical foundation of functional languages such as Haskell, ML and Scheme and, more importantly for this course, it is the starting point for the study of type systems, programming language semantics and the type theory underlying proof assistants such as Lean. In this chapter we study the untyped version of the calculus. Our goals are:

  • to present the syntax of the untyped lambda calculus together with the notions of free variables, bound variables and alpha-equivalence;

  • to present the call-by-value operational semantics;

  • to show how booleans, natural numbers and functions over them can be represented using nothing but functions (the Church encodings);

  • to present De Bruijn notation and the substitution operation in that representation;

  • to discuss the main points of a Haskell implementation, available in haskell/src/Untyped.

1.5.1. Syntax

The grammar of the untyped lambda calculus is extremely simple. A term is a variable, an abstraction or an application:

t \;::=\; x \;\mid\; \lambda x.\, t \;\mid\; t\;t

Each of these forms has an intuitive reading:

  • x is a variable, that is, an arbitrary identifier;

  • \lambda x.\, t is an abstraction: an (anonymous) function with parameter x and body t;

  • t_1\;t_2 is an application: the function t_1 applied to the argument t_2.

There are no numbers, booleans, conditionals or loops: all of these will be encoded using functions alone, as we shall see.

1.5.1.1. Notational conventions

To avoid an excess of parentheses, we adopt three standard conventions. First, application associates to the left: t_1\;t_2\;t_3 \;=\; (t_1\;t_2)\;t_3 Second, the body of an abstraction extends as far to the right as possible: \lambda x.\;t_1\;t_2 \;=\; \lambda x.\;(t_1\;t_2) Finally, consecutive abstractions are abbreviated by a single lambda with several parameters: \lambda x\,y\,z.\;t \;=\; \lambda x.\,\lambda y.\,\lambda z.\,t

Note that multi-argument functions are not primitive: a "two-argument" function is a function that takes the first argument and returns a function expecting the second. This technique is known as currying, in honour of Haskell Curry, and it is precisely how Haskell and Lean treat functions of several arguments.

1.5.1.2. Free and bound variables

An occurrence of a variable x in a term t is said to be bound if it lies within the scope of an abstraction \lambda x; otherwise the occurrence is free. For instance, in the term \lambda x.\;x\;y, the variable x is bound (by the outermost lambda) while y is free. The same variable may occur both free and bound in a single term: in x\;(\lambda x.\;x) the first occurrence of x is free and the second one is bound.

The set \text{FV}(t) of free variables of a term is defined by recursion on its structure: \begin{array}{lcl} \text{FV}(x) & = & \{x\} \\ \text{FV}(\lambda x.\,t) & = & \text{FV}(t) \setminus \{x\} \\ \text{FV}(t_1\;t_2) & = & \text{FV}(t_1) \cup \text{FV}(t_2) \end{array} A term with no free variables, that is, with \text{FV}(t) = \emptyset, is called closed, or a combinator. For example, \text{FV}(\lambda x.\,x\;y) = \text{FV}(x\;y) \setminus \{x\} = \{y\}, whereas \lambda x.\,\lambda y.\,x is closed.

1.5.1.3. Alpha-equivalence

The name chosen for a function's parameter is irrelevant: the identity function is the same whether we write it as \lambda x.\,x or as \lambda y.\,y. We say that two terms are alpha-equivalent, written t =_\alpha t', when they differ only in the names of their bound variables: \lambda x.\;x \;=_\alpha\; \lambda y.\;y \;=_\alpha\; \lambda z.\;z

In the lambda calculus, alpha-equivalent terms are regarded as identical. Renaming, however, must be done with care: \lambda x.\,x\;y is alpha-equivalent to \lambda z.\,z\;y, but not to \lambda y.\,y\;y — when renaming x to y, the free variable y would be captured by the lambda, changing the meaning of the term. This concern with capture will resurface in the definition of substitution and is the motivation for De Bruijn notation.

1.5.2. Semantics: call-by-value

The semantics of the lambda calculus is given by a reduction system that defines how terms are simplified. The fundamental rule is beta-reduction: (\lambda x.\;t_1)\;t_2 \;\longrightarrow\; [x \mapsto t_2]\;t_1 It reads: applying \lambda x.\;t_1 to the argument t_2 reduces to the body t_1 with the free occurrences of x replaced by t_2. A term of the form (\lambda x.\,t_1)\;t_2 is called a redex (from reducible expression). For example: (\lambda x.\;x\;x)\;(\lambda y.\;y) \;\longrightarrow\; (\lambda y.\;y)\;(\lambda y.\;y) \;\longrightarrow\; \lambda y.\;y

The substitution [x \mapsto s]\,t must avoid variable capture. It is defined by \begin{array}{lcll} [x \mapsto s]\,x & = & s & \\ [x \mapsto s]\,y & = & y & \text{if } y \neq x\\ [x \mapsto s]\,(t_1\;t_2) & = & ([x \mapsto s]\,t_1)\;([x \mapsto s]\,t_2) & \\ [x \mapsto s]\,(\lambda x.\,t) & = & \lambda x.\,t & \\ [x \mapsto s]\,(\lambda y.\,t) & = & \lambda y.\,[x \mapsto s]\,t & \text{if } y \neq x \text{ and } y \notin \text{FV}(s) \end{array} and, when y \in \text{FV}(s), we first rename the bound y to a fresh name (using alpha-equivalence) and only then proceed.

1.5.2.1. Evaluation strategies

A term may contain several redexes, and beta-reduction by itself does not say which one to reduce. An evaluation strategy fixes that choice. In the call-by-value (CBV) strategy, used by most programming languages:

  • the argument is fully evaluated before being passed to the function;

  • there is no reduction under abstractions — the body of a function is only evaluated once the function is applied.

The values of CBV are therefore just the abstractions: v \;::=\; \lambda x.\;t

The one-step reduction relation t \longrightarrow t' is defined by the following three rules: \frac{t_1 \;\longrightarrow\; t_1'}{t_1\;t_2 \;\longrightarrow\; t_1'\;t_2}\;\text{(E-App1)} \qquad \frac{t_2 \;\longrightarrow\; t_2'}{v_1\;t_2 \;\longrightarrow\; v_1\;t_2'}\;\text{(E-App2)} (\lambda x.\;t_{12})\;v_2 \;\longrightarrow\; [x \mapsto v_2]\;t_{12}\;\text{(E-Beta)}

Rule E-App1 says that we reduce the function first; E-App2 says that, once the function is a value, we reduce the argument; and E-Beta fires beta-reduction only when both function and argument are already values. Note that the metavariables v_1 in E-App2 and v_2 in E-Beta restrict when the rules apply: this is what makes evaluation deterministic — at each step, at most one rule applies.

As an example, consider the term (\lambda x.\;x)\;((\lambda y.\;y)\;(\lambda z.\;z)). The function is already a value, but the argument is not; hence we apply E-App2, whose premise is obtained by E-Beta: \frac{(\lambda y.\;y)\;(\lambda z.\;z) \;\longrightarrow\; \lambda z.\;z}{(\lambda x.\;x)\;((\lambda y.\;y)\;(\lambda z.\;z)) \;\longrightarrow\; (\lambda x.\;x)\;(\lambda z.\;z)}\;\text{(E-App2)} Now both function and argument are values, and one E-Beta step completes the evaluation: (\lambda x.\;x)\;(\lambda z.\;z) \;\longrightarrow\; \lambda z.\;z \;\text{(E-Beta)}

We write t \longrightarrow^* t' for the reflexive and transitive closure of \longrightarrow, that is, when t reduces to t' in zero or more steps.

1.5.2.2. Normal forms and non-termination

A term is in normal form when no reduction rule applies to it. Not every term has a normal form. The classic example is the combinator \Omega = (\lambda x.\;x\;x)\;(\lambda x.\;x\;x), which reduces to itself: (\lambda x.\;x\;x)\;(\lambda x.\;x\;x) \;\longrightarrow\; (\lambda x.\;x\;x)\;(\lambda x.\;x\;x) \;\longrightarrow\;\cdots The combinator \Omega is the simplest non-terminating term. Its existence is the price of expressiveness: a Turing-complete calculus necessarily admits computations that do not terminate. In the next chapter we will see that a type system can rule out terms such as \Omega, at the cost of some expressiveness.

1.5.3. Church encodings

If the lambda calculus has only functions, how can we represent data? Church's answer is to encode each data type by its behaviour: a piece of data is represented by the way it can be used.

1.5.3.1. Booleans

A boolean serves to choose between two alternatives. Thus we represent a boolean as a function of two arguments that returns one of them: \begin{array}{lcl} \mathbf{true} & = & \lambda t.\,\lambda f.\;t \\ \mathbf{false} & = & \lambda t.\,\lambda f.\;f \end{array} The conditional simply hands the branches over to the boolean: \mathbf{if} \;=\; \lambda b.\,\lambda t.\,\lambda f.\;b\;t\;f Let us check that \mathbf{if}\;\mathbf{true}\;M\;N \longrightarrow^* M: \begin{array}{cl} & (\lambda b.\,\lambda t.\,\lambda f.\;b\;t\;f)\;\mathbf{true}\;M\;N \\ \longrightarrow^* & \mathbf{true}\;M\;N \\ = & (\lambda t.\,\lambda f.\;t)\;M\;N \\ \longrightarrow^* & M \end{array} (Here we assume that M and N are values, as required by the CBV strategy.) The logical operations are defined in a similar way: \begin{array}{lcl} \mathbf{and} & = & \lambda b_1.\,\lambda b_2.\;b_1\;b_2\;\mathbf{false}\\ \mathbf{or} & = & \lambda b_1.\,\lambda b_2.\;b_1\;\mathbf{true}\;b_2 \\ \mathbf{not} & = & \lambda b.\;b\;\mathbf{false}\;\mathbf{true} \end{array} The intuition for \mathbf{and} is: "if b_1 is true, the result is b_2; otherwise it is false". Let us check that \mathbf{not}\;\mathbf{true} \longrightarrow^* \mathbf{false}: \begin{array}{cl} & (\lambda b.\;b\;\mathbf{false}\;\mathbf{true})\;\mathbf{true} \\ \longrightarrow & \mathbf{true}\;\mathbf{false}\;\mathbf{true} \\ = & (\lambda t.\,\lambda f.\;t)\;\mathbf{false}\;\mathbf{true} \\ \longrightarrow^* & \mathbf{false} \end{array}

1.5.3.2. Natural numbers

Church numerals encode the natural number n as the act of iterating a function n times: \begin{array}{lcl} \mathbf{0} & = & \lambda f.\,\lambda x.\;x \\ \mathbf{1} & = & \lambda f.\,\lambda x.\;f\;x \\ \mathbf{2} & = & \lambda f.\,\lambda x.\;f\,(f\;x) \\ \mathbf{n} & = & \lambda f.\,\lambda x.\;\underbrace{f\,(f\,(\cdots(f}_{n}\;x)\cdots)) \end{array} In other words, the numeral \mathbf{n} takes a function f and a starting point x and applies f to x exactly n times. The successor applies f one more time: \mathbf{succ} = \lambda n.\,\lambda f.\,\lambda x.\;f\,(n\;f\;x) For example, \mathbf{succ}\;\mathbf{1} reduces to \mathbf{2} (also reducing under lambdas in the second step): \begin{array}{cl} & (\lambda n.\,\lambda f.\,\lambda x.\;f\,(n\;f\;x))\;\mathbf{1} \\ \longrightarrow & \lambda f.\,\lambda x.\;f\,(\mathbf{1}\;f\;x) \\ \longrightarrow^* & \lambda f.\,\lambda x.\;f\,(f\;x) \;=\; \mathbf{2} \end{array} Addition applies f m times to the result of applying f n times to x; multiplication iterates m times the function n\;f (which, in turn, applies f n times): \begin{array}{lcl} \mathbf{plus} & = & \lambda m.\,\lambda n.\,\lambda f.\,\lambda x.\;m\;f\;(n\;f\;x) \\ \mathbf{mult} & = & \lambda m.\,\lambda n.\,\lambda f.\;m\,(n\;f) \end{array} Finally, the zero test iterates, starting from \mathbf{true}, a function that always returns \mathbf{false}. If the function is applied at least once, the result will be \mathbf{false}: \mathbf{iszero} = \lambda n.\;n\;(\lambda x.\;\mathbf{false})\;\mathbf{true} Indeed, for the numeral zero: \begin{array}{cl} & (\lambda n.\;n\;(\lambda x.\;\mathbf{false})\;\mathbf{true})\;\mathbf{0} \\ \longrightarrow & \mathbf{0}\;(\lambda x.\;\mathbf{false})\;\mathbf{true} \\ = & (\lambda f.\,\lambda x.\;x)\;(\lambda x.\;\mathbf{false})\;\mathbf{true} \\ \longrightarrow^* & \mathbf{true} \end{array}

1.5.3.3. Church numerals in Lean

Since Lean is itself a (typed) lambda calculus, we can transcribe the encodings above directly. For the terms to be well typed we need to give the numerals a type: a Church numeral is a function that, for any type \alpha, takes f : \alpha \to \alpha and x : \alpha and returns an \alpha.

namespace Ch04 def CBool := ∀ (α : Type), α → α → α def ctrue : CBool := fun _ t _ => t def cfalse : CBool := fun _ _ f => f def cnot (b : CBool) : CBool := fun α t f => b α f t def cand (b₁ b₂ : CBool) : CBool := fun α t f => b₁ α (b₂ α t f) f def CBool.toBool (b : CBool) : Bool := b Bool true false def Church := ∀ (α : Type), (α → α) → α → α def czero : Church := fun _ _ x => x def csucc (n : Church) : Church := fun α f x => f (n α f x) def cplus (m n : Church) : Church := fun α f x => m α f (n α f x) def cmult (m n : Church) : Church := fun α f => m α (n α f) def ciszero (n : Church) : CBool := fun α t f => n α (fun _ => f) t def Church.toNat (n : Church) : Nat := n Nat (· + 1) 0 def cone : Church := csucc czero def ctwo : Church := csucc cone def cthree : Church := csucc ctwo

The function Church.toNat converts a Church numeral into a Lean natural number: we simply choose f to be the successor and x to be zero. We can then test the operations:

5#eval (cplus ctwo cthree).toNat 6#eval (cmult ctwo cthree).toNat true#eval (ciszero czero).toBool false#eval (cand ctrue (cnot ctrue)).toBool
5
6
true
false

Beyond testing, we can prove properties. Since the definitions are functions, the equalities below hold by pure computation (reduction), and the rfl tactic checks them:

example : (cplus ctwo ctwo).toNat = 4 := rfl example (n : Church) : (csucc n).toNat = n.toNat + 1 := rfl example (m n : Church) : (cplus m n).toNat = m Nat (· + 1) n.toNat := rfl

1.5.4. De Bruijn notation

In the named notation, alpha-equivalent terms are considered equal but have different representations. This complicates any implementation: checking alpha-equivalence and performing capture-avoiding substitution are delicate operations and a frequent source of bugs. De Bruijn notation, proposed by Nicolaas de Bruijn in 1972 in the context of the Automath system, eliminates variable names altogether, replacing them with numeric indices.

1.5.4.1. De Bruijn indices

The De Bruijn index of a variable occurrence is the number of lambdas separating it from the lambda that binds it. Thus index 0 refers to the nearest lambda, 1 to the next one, and so on: \begin{array}{lcl} \lambda x.\;x & \leadsto & \lambda.\;0 \\ \lambda x.\,\lambda y.\;x & \leadsto & \lambda.\,\lambda.\;1 \\ \lambda x.\,\lambda y.\;y & \leadsto & \lambda.\,\lambda.\;0 \\ \lambda x.\,\lambda y.\;x\;y & \leadsto & \lambda.\,\lambda.\;1\;0 \end{array} The great advantage is that alpha-equivalent terms have the same representation: \lambda x.\;x \;=_\alpha\; \lambda y.\;y \;=_\alpha\; \lambda z.\;z \;\leadsto\; \lambda.\;0 Hence alpha-equivalence becomes syntactic equality. The grammar of terms becomes: t \;::=\; n \;\mid\; \lambda.\,t \;\mid\; t\;t \qquad (n \in \mathbb{N})

Note that the same variable may have different indices at different points of the term: in \lambda x.\,x\;(\lambda y.\,x), the first occurrence of x has index 0 and the second has index 1, giving \lambda.\,0\;(\lambda.\,1). Free variables are represented by indices that exceed the number of enclosing lambdas; they point into an external context.

1.5.4.2. Shift

When performing a substitution, a term may be moved inside (or outside) of lambdas, and the indices of its free variables must be adjusted accordingly. The shift operator \uparrow^d_c\,t increments by d every free index of t that is greater than or equal to the cutoff c. The cutoff ensures that the variables bound inside t itself are left untouched: \begin{array}{lcl} \uparrow^d_c\,k & = & \begin{cases} k & \text{if } k < c \\ k + d & \text{if } k \geq c \end{cases} \\[1em] \uparrow^d_c(\lambda.\,t) & = & \lambda.\,\uparrow^d_{c+1} t \\ \uparrow^d_c(t_1\;t_2) & = & (\uparrow^d_c t_1)\;(\uparrow^d_c t_2) \end{array} When going under a lambda the cutoff is incremented, since index c now refers to a variable bound by that lambda. For example, \uparrow^2_0(\lambda.\,0\;1) = \lambda.\,0\;3: index 0 is bound and stays unchanged; index 1 is free and gets shifted.

1.5.4.3. Substitution

The substitution [j \mapsto s]\,t replaces index j with the term s in t: \begin{array}{lcl} [j \mapsto s]\,k & = & \begin{cases} s & \text{if } k = j \\ k & \text{otherwise} \end{cases} \\[1em] [j \mapsto s]\,(\lambda.\,t) & = & \lambda.\,[j{+}1 \mapsto \uparrow^1_0 s]\,t \\ [j \mapsto s]\,(t_1\;t_2) & = & ([j \mapsto s]\,t_1)\;([j \mapsto s]\,t_2) \end{array} The interesting case is the abstraction: under an additional lambda, the variable we want to replace now has index j + 1, and the free variables of s must also be shifted by one so that they keep pointing to the same outer binders. There is no need whatsoever to rename variables: capture is avoided automatically by the shifts.

1.5.4.4. Beta-reduction

With shift and substitution in hand, beta-reduction in De Bruijn notation is: (\lambda.\,t_1)\;t_2 \;\longrightarrow\; \uparrow^{-1}_0\!\left([0 \mapsto \uparrow^1_0\,t_2]\;t_1\right) Two adjustments deserve an explanation. The argument is shifted by \uparrow^1_0\,t_2 because, once placed in the body t_1, it lies (momentarily) under the lambda being eliminated; its free indices must be incremented. After the substitution that lambda disappears, so the free indices that pointed "beyond" it must be decremented — hence the outer \uparrow^{-1}_0.

For example, the reduction of (\lambda.\;0)\;(\lambda.\;0) is: \uparrow^{-1}_0\!\left([0 \mapsto \uparrow^1_0(\lambda.\;0)]\;0\right) = \uparrow^{-1}_0\!\left([0 \mapsto \lambda.\;0]\;0\right) = \uparrow^{-1}_0\!(\lambda.\;0) = \lambda.\;0

An example in which the shift is essential: consider \lambda.\,(\lambda.\,\lambda.\,1)\;0, that is, \lambda z.\,(\lambda x.\,\lambda y.\,x)\;z. Reducing the inner redex, we should obtain \lambda z.\,\lambda y.\,z, i.e., \lambda.\,\lambda.\,1. Indeed, when substituting index 0 in the body \lambda.\,1, we go under one lambda and the substituted term \uparrow^1_0 0 = 1 is shifted again to 2; afterwards, the shift \uparrow^{-1}_0 brings it back to 1.

1.5.4.5. Converting between representations

Humans prefer names; implementations prefer indices. To convert a named term into a De Bruijn term we use a context \Gamma: a list of variable names, with the most recently bound variable at the front. The index of a variable is its position in the context: \begin{array}{lcl} \text{conv}(\Gamma, x) & = & i \;\text{ where } \Gamma[i] = x \\ \text{conv}(\Gamma, \lambda x.\,t) & = & \lambda.\;\text{conv}(x:\Gamma,\, t) \\ \text{conv}(\Gamma, t_1\;t_2) & = & \text{conv}(\Gamma,t_1)\;\text{conv}(\Gamma,t_2) \end{array} If x occurs several times in \Gamma, we take the first occurrence (the innermost one), which correctly implements variable shadowing. The inverse conversion recovers names from the context and invents fresh names for the lambdas: \begin{array}{lcl} \text{conv}^{-1}(\Gamma, k) & = & \Gamma[k] \\ \text{conv}^{-1}(\Gamma, \lambda.\,t) & = & \lambda x.\;\text{conv}^{-1}(x:\Gamma,\,t) \quad \text{where } x \notin \Gamma\\ \text{conv}^{-1}(\Gamma, t_1\;t_2) & = & \text{conv}^{-1}(\Gamma,t_1)\;\text{conv}^{-1}(\Gamma,t_2) \end{array}

1.5.4.6. De Bruijn terms in Lean

The definitions above can be implemented directly. In Lean we represent terms by an inductive type and define shift, substitution and beta-reduction. We use an integer displacement d to allow negative shifts. The auxiliary function Term.pp merely prints terms in the notation used in the text.

inductive Term where | var : Nat → Term | lam : Term → Term | app : Term → Term → Term deriving DecidableEq open Term -- printing in the style λ. 1 (1 0) def Term.pp : Term → String | var k => toString k | lam t => "λ. " ++ t.pp | app (lam t) u => "(λ. " ++ t.pp ++ ") " ++ ppArg u | app t u => t.pp ++ " " ++ ppArg u where ppArg : Term → String | var k => toString k | t => "(" ++ t.pp ++ ")" instance : Repr Term where reprPrec t _ := t.pp def shift (d : Int) : Nat → Term → Term | c, var k => if k < c then var k else var (k + d).toNat | c, lam t => lam (shift d (c + 1) t) | c, app t u => app (shift d c t) (shift d c u) def subst (j : Nat) (s : Term) : Term → Term | var k => if k = j then s else var k | lam t => lam (subst (j + 1) (shift 1 0 s) t) | app t u => app (subst j s t) (subst j s u) def beta (body arg : Term) : Term := shift (-1) 0 (subst 0 (shift 1 0 arg) body)

We can test the example from the previous section: reducing the redex (\lambda.\,\lambda.\,1)\;0 under an outer lambda amounts to computing beta (lam (var 1)) (var 0).

λ. 1#eval beta (lam (var 1)) (var 0) λ. 0#eval beta (var 0) (lam (var 0))
λ. 1
λ. 0

We can also prove simple properties, such as the fact that shifting by zero leaves the term unchanged:

theorem shift_zero (t : Term) (c : Nat) : shift 0 c t = t := t:Termc:Nat⊢ shift 0 c t = t induction t generalizing c with k:Natc:Nat⊢ shift 0 c (var k) = var k All goals completed! 🐙 t:Termih:∀ (c : Nat), shift 0 c t = tc:Nat⊢ shift 0 c t.lam = t.lam All goals completed! 🐙 t:Termu:Termiht:∀ (c : Nat), shift 0 c t = tihu:∀ (c : Nat), shift 0 c u = uc:Nat⊢ shift 0 c (t.app u) = t.app u All goals completed! 🐙

1.5.5. Implementation in Haskell

The folder haskell/src/Untyped contains an interactive interpreter (REPL) for the untyped lambda calculus, which accepts terms both with names and with De Bruijn indices. Below we discuss its main points.

1.5.5.1. Data types

There are two representations of terms. The named representation (Untyped.Syntax.Named) follows the original grammar:

data Term
  = Var String       -- variable
  | Lam String Term  -- λx. t
  | App Term Term    -- t1 t2

The De Bruijn representation (Untyped.Syntax.DeBruijn) replaces names with indices and drops the parameter name from the Lam constructor:

data Term
  = Var Int      -- index
  | Lam Term     -- λ. t  (no name)
  | App Term Term

1.5.5.2. Conversions

The conversion from names to indices follows the function \text{conv}. The context is a list of names and findIndex returns the first position at which the name occurs. Since the conversion may fail (unbound variable), the result lives in the Either String monad, and the applicative operators <$> and <*> propagate errors:

type Context = [String]

fromNamed :: Context -> N.Term -> Either String Term
fromNamed ctx (N.Var x) =
  case findIndex (== x) ctx of
    Just i  -> Right (Var i)
    Nothing -> Left ("Unbound variable: " ++ x)
fromNamed ctx (N.Lam x body) =
  Lam <$> fromNamed (x : ctx) body
fromNamed ctx (N.App t1 t2) =
  App <$> fromNamed ctx t1 <*> fromNamed ctx t2

The inverse conversion generates a fresh name for each lambda (freshName picks the first name in the sequence a, b, ..., z, a1, ... that does not occur in the context); free indices exceeding the context are displayed as _k:

toNamed :: Context -> Term -> N.Term
toNamed ctx (Var i)
  | i < length ctx = N.Var (ctx !! i)
  | otherwise      = N.Var ("_" ++ show i)
toNamed ctx (Lam body) =
  let name = freshName ctx
  in  N.Lam name (toNamed (name : ctx) body)
toNamed ctx (App t1 t2) =
  N.App (toNamed ctx t1) (toNamed ctx t2)

1.5.5.3. Shift, substitution and beta-reduction

The functions in the module Untyped.Interpreter are literal transcriptions of the equations of the previous section:

shift :: Int -> Int -> Term -> Term
shift d c (Var k)
  | k >= c    = Var (k + d)
  | otherwise = Var k
shift d c (Lam body)  = Lam (shift d (c + 1) body)
shift d c (App t1 t2) = App (shift d c t1) (shift d c t2)

subst :: Int -> Term -> Term -> Term
subst j s (Var k)
  | k == j    = s
  | otherwise = Var k
subst j s (Lam body)  = Lam (subst (j+1) (shift 1 0 s) body)
subst j s (App t1 t2) = App (subst j s t1) (subst j s t2)

betaReduce :: Term -> Term -> Term
betaReduce t1 t2 = shift (-1) 0 (subst 0 (shift 1 0 t2) t1)

1.5.5.4. Evaluation

The interpreter does not use the CBV strategy but rather normal order (leftmost-outermost): it always reduces the outermost, leftmost redex, including under lambdas. This strategy has the property of finding the normal form of a term whenever one exists, and it allows us to display results such as \mathbf{succ}\;\mathbf{1} \longrightarrow^* \mathbf{2}, which require reduction under abstractions. The function step performs one reduction step, returning Nothing if the term is already in normal form:

step :: Term -> Maybe Term
step (App (Lam body) t2) = Just (betaReduce body t2)
step (App t1 t2) =
  case step t1 of
    Just t1' -> Just (App t1' t2)
    Nothing  -> App t1 <$> step t2
step (Lam body) = Lam <$> step body
step _          = Nothing

Compare this with the CBV rules: the first case fires beta-reduction without requiring the argument to be a value; the second tries to reduce the function and, if it is already normal, the argument; the third reduces under the lambda — something forbidden in CBV.

Since evaluation may fail to terminate (think of \Omega), the function eval takes a step limit. The result indicates whether a normal form was reached (and in how many steps) or whether the limit was hit:

data EvalResult
  = NormalForm Term Int  -- normal form + number of steps
  | StepLimit  Term      -- limit reached

eval :: Int -> Term -> EvalResult
eval maxSteps = go 0
  where
    go n t
      | n >= maxSteps = StepLimit t
      | otherwise =
          case step t of
            Nothing -> NormalForm t n
            Just t' -> go (n+1) t'

In the REPL (run with cabal run untyped), each term entered is displayed in both representations and reduced to normal form, with a limit of one million steps:

named> (\x. x) (\y. y)
  Input (named):    (λx. x) (λy. y)
  Input (De Bruijn): (λ. 0) (λ. 0)
  Normal form (1 step):
    Named:    λy. y
    De Bruijn: λ. 0

The same normal-order strategy can be written in Lean, using a "fuel" parameter to guarantee that the function terminates:

def step : Term → Option Term | app (lam b) u => some (beta b u) | app t u => match step t with | some t' => some (app t' u) | none => (app t ·) <$> step u | lam b => lam <$> step b | var _ => none def eval : Nat → Term → Term | 0, t => t | n + 1, t => match step t with | some t' => eval n t' | none => t -- succ = λ n f x. f (n f x); one = λ f x. f x def dbSucc : Term := lam (lam (lam (app (var 1) (app (app (var 2) (var 1)) (var 0))))) def dbOne : Term := lam (lam (app (var 1) (var 0))) λ. λ. 1 (1 0)#eval eval 100 (app dbSucc dbOne)
λ. λ. 1 (1 0)

The result is \lambda.\,\lambda.\,1\;(1\;0), that is, \lambda f.\,\lambda x.\,f\,(f\;x) = \mathbf{2}, as expected.

end Ch04

1.5.6. Exercises

  1. Compute \text{FV}(t) for t = (\lambda x.\,x\;y)\;(\lambda y.\,y\;z) and indicate, for each variable occurrence, whether it is free or bound.

  2. Determine which pairs of terms are alpha-equivalent: \lambda x.\,\lambda y.\,x\;y and \lambda y.\,\lambda x.\,y\;x; \lambda x.\,x\;z and \lambda z.\,z\;z.

  3. Show the complete sequence of CBV steps, indicating the rule used at each step, for the term (\lambda x.\,\lambda y.\,x)\;((\lambda z.\,z)\;(\lambda w.\,w)).

  4. Verify, by reduction, that \mathbf{and}\;\mathbf{true}\;\mathbf{false} \longrightarrow^* \mathbf{false} and that \mathbf{or}\;\mathbf{false}\;\mathbf{true} \longrightarrow^* \mathbf{true}.

  5. Define exponentiation of Church numerals, \mathbf{exp}\;m\;n = m^n. (Hint: in the untyped lambda calculus \lambda m.\,\lambda n.\,n\;m suffices.) Implement it in Lean on the type Church and test it with toNat. Why is the Lean version harder to type?

  6. Define Church pairs \mathbf{pair} = \lambda a.\,\lambda b.\,\lambda s.\,s\;a\;b and the projections \mathbf{fst} and \mathbf{snd}. Use them to define the predecessor of Church numerals.

  7. Convert to De Bruijn notation: \lambda x.\,\lambda y.\,\lambda z.\,x\;z\;(y\;z) and \lambda f.\,(\lambda x.\,f\;(x\;x))\;(\lambda x.\,f\;(x\;x)).

  8. Compute \uparrow^1_0(\lambda.\,\lambda.\,0\;2\;3) and [0 \mapsto 1]\,(\lambda.\,0\;1).

  9. Prove in Lean that shift d c (shift 0 c t) = shift d c t and, more challenging, that shift (-1) c (shift 1 c t) = t.

  10. Write, in Lean or Haskell, an evaluation function that follows the CBV rules exactly (E-App1, E-App2, E-Beta), without reducing under lambdas, and compare its behaviour with that of normal order on the term (\lambda x.\,\lambda y.\,y)\;\Omega.