The Lambda Calculus
So far, the languages we’ve seen – LetLang, IteLang, CalcLang – are tiny, and seem unrepresentative of the kinds of languages that we would actually prgram in. We will change that today by seeing the smallest interesting programming language: the lambda calculus. Despite its simplicity — barely more complicated than LetLang — we will see it is Turing-complete: it is capable (more or less) of representing any program your computer can run. This combination of expressiveness and simplicity has made it the historical and intellectual starting point for much of programming languages.
Syntax
Written as a grammar, the lambda calculus is as follows:
<expr> := <ident>
| λ <ident>. <expr>
| <expr> <expr>
| ( <expr> )
<ident> := x | y | ...
That is, expressions in the lambda calculus are only composed of only three forms:
- Variables;
- Abstraction, written as
λ x. e, wherexis an identifier andeis an expression; and - Application, written as
e e', whereeande'are both expressions.
The lambda calculus is, in essence, the theory of functions. Abstraction creates functions, while application calls them. Let’s see some terms in the lambda calculus:
- \( \lambda x. x \): this represents the identity function, since it returns whatever it is called with.
- \( (\lambda x. x) (\lambda x. x) \): calling the identity function on itself.
- \( \lambda x. \lambda y. x \): a function which, given \( x \), returns another function that, when given \( y \), returns \( x \); and
- \( \lambda x. \lambda y. y \): a function which, given \( x \), returns another function that, when given \( y \), returns \( y \).
You might have noticed by now that the lambda calculus is quite similar to how anonymous functions work in real languages. This is not an accident: the lambda calculus — which goes back to Alonzo Church in the 30s — is the historical predecessor of many modern programming languages. We can see this in anonymous functions in Lait:
import Lait
#lait
-- In Lait, we use "fun" instead of a lambda symbol, and use "=>" instead of a dot.
#check (fun x => x) (fun x => x)>> a -> a
As well as in Python:
>>> id = lambda x: x
>>> id(id)
<function <lambda> at 0x100b48f70>
>>> id(id)(32)
32
The beauty of the lambda calculus is its combination of simplicity and expressiveness. As we will see soon, the lambda calculus is Turing-complete, meaning that it can define any computable function. At the same time, it is extremely simple, and can be embedded in Lait as follows:
type Exp := | EVar (var : String)
| ELam (var : String) (body : Exp)
| EApp (e1 : Exp) (e2 : Exp)
Reading Lambda Calculus on Paper
It is extremely important that you understand intuitively how to read lambda calculus terms on paper, so we will spend some time on that now. Going back to our grammar, see that the case for application — given by putting lambda terms side by side — is ambiguous. (This is the same problem as we had for addition in the second lecture.) We resolve this ambiguity by making application be left-associative, which means that \( e_1\ e_2\ e_3 \) is always parsed as \( (e_1\ e_2)\ e_3 \), rather than \( e_1\ (e_2\ e_3) \). This allows us to think of nested functions as multi-argument ones: for example, \( (\lambda x. \lambda y. x\ y)\ z\ w \) is the same as \( ((\lambda x. \lambda y. x\ y)\ z)\ w \), which means that we will run the body \( x\ y \), where the argument \( z \) stands for \( x \) and \( w \) stands for \( y \). This is the same as what happens in Lait:
#eval (fun x => fun y => x + y) 2 3
The other important rule is that the scope of the argument to a function is as far as it will go. Thus, \( \lambda x. x\ x\ x \) is the same as \( \lambda x. (x\ x\ x) \), rather than (say) \( (\lambda x. x\ x)\ x \).
The grammar of the lambda calculus is probably unfamiliar, so let’s see some concrete examples:
| Surface Syntax | Abstract Syntax (in Lait) |
|---|---|
| \( x \) | EVar "x" |
| \( \lambda x. x \) | ELam "x" (EVar "x") |
| \( \lambda x. \lambda y. y \) | ELam "x" (ELam "y" (EVar "y")) |
| \( x\ y \) | EApp (EVar "x") (EVar "y") |
| \( x\ y\ z \) | EApp (EApp (EVar "x") (EVar "y")) (EVar "z") |
| \( (x\ y)\ z \) | EApp (EApp (EVar "x") (EVar "y")) (EVar "z") |
| \( x\ (y\ z) \) | EApp (EVar "x") (EApp (EVar "y") (EVar "z")) |
Open and Closed Terms
A very important idea in the lambda calculus (and every other language that has variables) is the distinction between closed and open terms. A term in the lambda calculus is closed if every variable \( x \) in the program is bound by a corresponding abstraction \( \lambda x.\ \), and open if there is a variable that does not have a corresponding abstraction. Let’s see some examples:
| Expression | Closed or Open? |
|---|---|
| \( x \) | Open |
| \( \lambda x. x \) | Closed |
| \( \lambda x. y \) | Open |
| \( \lambda x. \lambda y. y \) | Closed |
| \( (\lambda x. x) x \) | Open! |
| \( \lambda x. \lambda x. x \) | Closed |
Throughout the class, we will almost entirely be focused on closed terms. Thus, we will give a semantics below to \( (\lambda x. x)\ (\lambda y. y) \), since it is closed, but won’t need to give a semantics to \( (\lambda x. y) (\lambda y. x) \), since it is an open program.
Semantics of the Lambda Calculus
Now that we have seen how to write lambda calculus terms, let’s see how to evaluate them. We will do so by first presenting a small-step semantics for lambda terms: that is, one where one step of evaluation happens at a time. This will be easier to understand by example on paper. Then, we will move to implementing a big-step interpreter for the lambda calculus.
Note
We will be presenting one of multiple different choices of semantics for the lambda calculus, called (weak) call-by-value. While other choices are possible, this is the only semantics we will need to consider.
There are two important cases to consider: abstraction and application. For abstraction, the important idea is that functions are values. Hence, lambda terms step to themselves:
\[ \lambda x. x \to \lambda x. x \]
Calling a function: \(\beta\)-reduction
Next, we need to consider application (i.e., function calls). The important case to consider is when both sides of the application \( e_1 e_2 \) are values (i.e., abstractions). In this case, we are in a situation where we want to step \( (\lambda x.\ e) v \), where \(v\) itself is an abstraction. To step this program, just as we did for LetLang, we will use substitution.
Whenever we have \( (\lambda x. e)\ v \), we step to \( e \) with the the value \(v\) substituted for the variable \(x\).
\[ (\lambda x. x)\ (\lambda y. \lambda z. y) \xrightarrow{\text{substitute $x := (\lambda y. \lambda z. y)$ in the body $x$}} (\lambda y. \lambda z. y) \]
Let’s break this down step by step:
- We first saw we are applying a function to another function. The first function here is \( \lambda x. x\).
- We then open up the first function to get a variable and a body. The variable is the identifier \( x \), while the body is the expression \( x \).
- We finally took that body, and substituted the second function, \( \lambda y. \lambda z. y \), in for the variable \( x \).
Let’s see another example: \[ (\lambda x. \lambda y. x)\ (\lambda z. z) \to \lambda y. \lambda z.\ z \]
- The first function is \( (\lambda x. \lambda y. x) \), whose variable is \( x \) and whose body is \( \lambda y. x \).
- We substituted \( \lambda z. z \) into the body for \( x \).
One more: \[ (\lambda x. \lambda y. y)\ (\lambda z. z) \to \lambda y. y \] In this case, the variable \(x\) is unused in the function’s body; hence, we substitute \(\lambda z.\ z\) in for \(x\) to receive \(\lambda y. y\).
This reduction step is called \(\beta\)-reduction.
A critical property of substitution is that it respects lexical scope with respect to shadowing. Thus, if we have a lambda term \( \lambda x. \lambda x. x \), the inner body \( x \) refers to the inner-most binding (i.e., the second one). Lait works the same way:
#eval (fun x => fun x => x + 1) 10 20>> 21
Stepping general expressions
Recall that for CalcLang, our small-step semantics for addition first
simplified the left-hand side, then the right-hand side. For example: ((1 + 2) + (3 + 4)) makes the following sequence of steps:
((1 + 2) + (3 + 4))
-->
(3 + (3 + 4))
-->
(3 + 7)
-->
10
Our stepping rules for the lambda calculus will behave the same way:
- If we are stepping a value \(v = \lambda x.\ e\), we return \(v\) itself.
- If we are stepping \((\lambda x.\ e)\ v\), we \(\beta\)-reduce: return \(e\) with \(v\) substituted for \(x\).
- If we are stepping \(e_1 e_2\), we step \(e_1\) until it is a value; then, step \(e_2\) until it is a value; then, the \(\beta\)-reduction rule applies.
As an example:
\[ \begin{aligned} & ((\lambda f. \lambda x. f\ x)\ (\lambda a. a))\ ((\lambda g. g)\ (\lambda b. \lambda c. c)) \xrightarrow{\text{Step $(\lambda f. \lambda x. f\ x)\ (\lambda a. a)$}} \\ & (\lambda x. (\lambda a. a)\ x)\ ((\lambda g. g)\ (\lambda b. \lambda c. c)) \xrightarrow{\text{Step $((\lambda g. g)\ (\lambda b. \lambda c. c))$}} \\ & (\lambda x. (\lambda a. a)\ x)\ (\lambda b. \lambda c. c) \xrightarrow{\text{Step outer application}} \\ & (\lambda a. a)\ (\lambda b. \lambda c. c) \xrightarrow{\text{Step outer application}} \\ & \lambda b. \lambda c. c. \end{aligned} \]
Note the order of events: we first stepped the left-hand side until it was a value, then the right-hand side, and only then did we \(\beta\)-reduce. Note also that \(\beta\)-reduction handed us back a term that was not yet a value, so we had to keep stepping.
A Big-Step Evaluator
Now that we see how the lambda calculus evaluates on paper, let’s turn this into a definitional interpreter (i.e., a big-step interpreter). As we saw for CalcLang, the difference between small-step and big-step is that big-step interpreters directly reduce to values (i.e., for us, abstractions) rather than intermediate computations.
We first need to define a substitution function for lambda expressions:
type Value := | VLam (var : String) (body : Exp)
def Value.toExp (v : Value) : Exp :=
match v with
| VLam var body => ELam var body
end
def subst (var : String) (assignment : Value) (body : Exp) : Exp :=
match body with
| EVar var' => if var == var' then Value.toExp assignment else EVar var'
| EApp e1 e2 => EApp (subst var assignment e1) (subst var assignment e2)
| ELam var' body' =>
if var == var' then
ELam var' body' -- Shadowing: no substitution
else
ELam var' (subst var assignment body')
end
def interp (e : Exp) : Value :=
match e with
| EVar _ => error "interp: got a variable"
| ELam var body => VLam var body
| EApp e1 e2 =>
let v1 := interp e1 in
let v2 := interp e2 in
let v1_substituted := match v1 with
| VLam var body => subst var v2 body
end
in
interp v1_substituted
end
Now, let’s see a few examples, before our big one from before:
#eval ELam "x" (EVar "x")>> ELam "x" (EVar "x")
#eval (EApp (ELam "x" (EVar "x")) (ELam "y" (EVar "y")))>> EApp (ELam "x" (EVar "x")) (ELam "y" (EVar "y"))
-- Breaking up the big terms into sub-pieces...
def Lf_Lx_fx := ELam "f" (ELam "x" (EApp (EVar "f") (EVar "x")))
def La_a := ELam "a" (EVar "a")
def Lg_g := ELam "g" (EVar "g")
def Lb_Lc_c := ELam "b" (ELam "c" (EVar "c"))
#eval interp (EApp (EApp Lf_Lx_fx La_a) (EApp Lg_g Lb_Lc_c))>> VLam "b" (ELam "c" (EVar "c"))
Some Features of the Lambda Calculus
It might not seem like the lambda calculus is a very expressive language, because of how small it is. So, let’s see how we can encode seemingly-richer features into the lambda calculus.
Multi-argument Functions
Lait lets us define functions like so
def callf f x := f x
Doing this in the lambda calculus is easy enough: we just write a function that defines another function: \[ \lambda f. \lambda x. f\ x \]
The process of transforming a multi-argument into nested functions of single arguments is called currying. In Lait, multi-argument functions are secretly just “curried” single-argument functions in disguise!
We can see this in the type of callf:
#check callf>> (a -> b) -> a -> b
Other languages have multi-argument functions baked more deeply into the language, like Python. However, you can reconstruct the curried function by using lambdas:
>>> def f(x, y):
... return x + y
...
>>> f(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() missing 1 required positional argument: 'y'
>>> f_curried = lambda x: lambda y: f(x,y)
>>> f_curried(3)
<function <lambda>.<locals>.<lambda> at 0x100b600d0>
>>> f_curried(3)(5)
8
Non-termination
One thing the lambda calculus seems to lack is any loop or way to recurse. However, even though the lambda calculus does not have an explicit looping construct, it is nevertheless possible to express loops!
Let’s do this by making a program that runs forever. To do this, we define a lambda calculus term \(\omega\) that takes a function as an argument and calls that function with itself:
\[ \omega := \lambda x. x\ x \]
Now, let’s see when we consider \(\omega\)’s big brother, \(\Omega\):
\[ \Omega ::= \omega\ \omega \]
Let’s try to run \(\Omega\). \(\Omega\) consists of an application between two values, so the \(\beta\)-reduction rule applies.
\[ (\lambda x. x\ x) (\lambda x. x\ x) \to (\lambda x. x\ x) (\lambda x. x\ x) \]
We get exactly back to where we started! Thus, \(\Omega\) is the while (true) { } of the lambda calculus.
Let’s see our Lait interpreter explode on it:
def omega := ELam "x" (EApp (EVar "x") (EVar "x"))
#eval interp (EApp omega omega)