Programming in, and Compiling To, the Lambda Calculus
As mentioned before, the lambda calculus is an expressive enough calculus for (theoretically) arbitrary computations. Today we’re going to see this play out in two different ways: via compiling into the lambda calculus, and via programming recursive functions in the lambda calculus. We will also learn about how lambda calculus terms can be considered equivalent to each other.
import Lait
#lait
BoolLang
First, we will see how a language with seemingly no relation to the lambda calculus can be compiled into it. Below, we have BoolLang:
type BoolLang :=
| BTrue
| BFalse
| BNot (e1 : BoolLang)
| BAnd (e1 : BoolLang) (e2 : BoolLang)
def BoolLang.interp (b : BoolLang) : Bool :=
match b with
| BTrue => true
| BFalse => false
| BNot e => not (BoolLang.interp e)
| BAnd e1 e2 => (BoolLang.interp e1) && (BoolLang.interp e2)
end
Let’s recall our lambda calculus definitions from last time:
type Exp := | EVar (var : String)
| ELam (var : String) (body : Exp)
| EApp (e1 : Exp) (e2 : Exp)
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
Compilers
Our goal is to show that the lambda calculus is expressive enough to encode BoolLang via a compiler. First, let’s discuss what this means: a compiler is a semantics-preserving translation from one language to another one. Compilers are one of the pillars of programming languages, so understanding them is important to understand programming languages in general.
Our compiler will be a function encode : BoolLang -> Exp.
Here, BoolLang is our source language, while the lambda calculus is our target language.
What does it mean for our compiler to be correct?
We will say that our compiler is correct if, for any BoolLang program e, if we compile e and run it as a lambda-calculus term, then we will get the same thing back
as if we run e in the BoolLang language, and encode the final result as a lambda-calculus term.
We can show this as the following diagram:
BoolCalc prog --------------------> lambda calc prog
| encode |
| |
| interp-bool | interp-lam
| |
| |
\/ encode \/
BoolCalc value -------------------> lambda calc value
When we draw a diagram like this, we mean that the square commutes: encoding and then interpreting in the lambda calculus is the same as interpreting in BoolLang and then encoding the final result.
Booleans in the Lambda Calculus
To write our function encode, we will need to choose a representation for the various BoolLang constructs, such as BTrue and BFalse.
We much pick lambda terms for these values. There are multiple possible encodings; we will study the following encodings for booleans introduced by Alonzo Church:
\[ \begin{aligned} \mathsf{Ltrue} &:= \lambda x. \lambda y. x \\ \mathsf{Lfalse} &:= \lambda x. \lambda y. y \end{aligned} \]
Hence, we are representing Ltrue and Lfalse as functions!
The central idea here is that Church booleans represent a choice. What is “true”? It is the decision that, when given two things, return the first.
Similarly, “false” is the decision that, when given two things, we return the second. To gain some intuition on this, think about how Booleans can be used in other languages, such as Lait:
#eval if true then 1 else 2>> 1
#eval if false then 1 else 2>> 2
The purpose of a boolean is to be used, and we use a boolean by doing a case split on it, via if/then/else. Hence, in the lambda calculus, we can represent a boolean by its behavior: a boolean is a two-argument function that behaves as its corresponding if/then/else. Hence, Ltrue X Y should evaluate to X, while Lfalse X Y should evaluate to Y, for any other lambda calculus terms X and Y.
Now that we have encoded BTrue and BFalse, we need to interpet the rest of BoolLang: BNot and BAnd.
Let’s first consider BNot. To encode BNot in the lambda calculus, we want a unary function: a term LNot in the lambda calculus so that LNot LTrue evaluates to LFalse, and LNot LFalse evaluates to LTrue. Let’s go back to our if/then/else intuition: how would we use if/then/else to compute not?
def myNot (b : Bool) : Bool :=
if b then false else true
#eval myNot true>> false
#eval myNot false>> true
Hence, we can take LNot to be the term which uses its argument to perform an if/then/else, and return LFalse on the true branch, and LTrue on the false branch:
\[ \mathsf{LNot} := \lambda b. b\ \mathsf{LFalse}\ \mathsf{LTrue} = \lambda b. b\ (\lambda x.\ \lambda y.\ y)\ (\lambda x. \lambda y. x) \]
Finally, let’s consider BAnd. Similarly, we want to encode it using if/then/else:
def myAnd (b1 : Bool) (b2 : Bool) : Bool :=
if b1 then b2 else false
#eval myAnd true true>> true
#eval myAnd true false>> false
#eval myAnd false true>> false
#eval myAnd false false>> false
This means we want the following definition: \[ \mathsf{LAnd} := \lambda b_1. \lambda b_2. b_1\ b_2\ \mathsf{LFalse}\ = \lambda b_1. \lambda b_2. b_1\ b_2\ (\lambda x. \lambda y. y) \]
Let’s now embed these into Lait, and see that they compute as expected:
def LTrue := ELam "x" (ELam "y" (EVar "x"))
def LFalse := ELam "x" (ELam "y" (EVar "y"))
def LNot := ELam "b" (EApp (EApp (EVar "b") LFalse) LTrue)
def LAnd := ELam "b1" (ELam "b2" (EApp (EApp (EVar "b1") (EVar "b2")) LFalse))
#eval interp (EApp LNot LTrue)>> VLam "x" (ELam "y" (EVar "y"))
#eval interp (EApp LNot LFalse)>> VLam "x" (ELam "y" (EVar "x"))
#eval interp (EApp (EApp LAnd LTrue) LTrue)>> VLam "x" (ELam "y" (EVar "x"))
#eval interp (EApp (EApp LAnd LTrue) LFalse)>> VLam "x" (ELam "y" (EVar "y"))
#eval interp (EApp (EApp LAnd LFalse) LTrue)>> VLam "x" (ELam "y" (EVar "y"))
#eval interp (EApp (EApp LAnd LFalse) LFalse)>> VLam "x" (ELam "y" (EVar "y"))
Now that we have our encoding in place, we can implement the compiler:
def encode (b : BoolLang) : Exp :=
match b with
| BTrue => LTrue
| BFalse => LFalse
| BNot b' =>
let e := encode b' in
EApp LNot e
| BAnd b1 b2 =>
let e1 := encode b1 in
let e2 := encode b2 in
EApp (EApp LAnd e1) e2
end
Let’s see that it works for arbitrary BoolLang programs:
def myProgram :=
BAnd
(BAnd
(BNot (BNot (BAnd BTrue (BNot BFalse))))
BTrue)
(BNot BFalse)
#eval BoolLang.interp myProgram>> true
#eval interp (encode myProgram)>> VLam "x" (ELam "y" (EVar "x"))
Equivalences of Lambda Calculus Terms
As you use our interpreter for lambda calculus terms, you will see that sometimes you might output one term while you expected another “equivalent” one. For example, consider the following program:
def id := ELam "x" (EVar "x")
def id_id := EApp id (ELam "y" (EVar "y"))
#eval interp id_id>> VLam "y" (EVar "y")
When we apply the identity function to the identity function, we get back the identity function. However, these programs are not equal from the perspective of Lait:
#eval id == (Value.toExp (interp id_id))>> false
Indeed, id uses the variable "x", while id_id ends up using the variable "y". While they are not literally the same code, they are of course the same in some way.
There are two ways in which we talk about equivalences of lambda terms, other than direct syntactic equality.
Alpha-Equivalence
The first is alpha equivalence. Put simply, two expressions are alpha equivalent if we can rename bound variables (those created by \(\lambda\)) to arise at the same term. For example, \(\lambda x. x\) and \(\lambda y. y\) are alpha equivalent. Below are some more terms, and whether they are alpha equivalent:
| Terms | Alpha Equivalent? |
|---|---|
| \( \lambda x. x\) and \( \lambda y. y\) | Yes |
| \( \lambda x. x \) and \( (\lambda x. x)\ (\lambda y. y) \) | No |
| \( \lambda x. \lambda y. x\) and \( \lambda y. \lambda x. y\) | Yes |
| \( \lambda x. \lambda y. x\) and \( \lambda y. \lambda x. x\) | No |
| \( \lambda x. \lambda y. x \) and \( \lambda x. \lambda x. x \) | No |
The first pair is alpha equivalent by renaming y to x. The second pair is not alpha equivalent because the two terms have a different structure; while the second evaluates to an alpha equivalent term to the first one, the two terms are not themselves alpha equivalent.
The third pair is alpha equivalent, because the second function is the same as the first by just permuting the variable names x and y.
However, if we change the structure of the lambda term, and return the second argument in the second term, but the first argument in the first term, they will not be alpha-equivalent.
Observational Equivalence
The second way we can think of lambda calculus terms as equivalent is observational equivalence, which states whether two lambda calculus terms behave the same. In this sense, \( \lambda x. x \) and \( (\lambda x. x)\ (\lambda y. y) \) are observationally equivalent: the left evaluates to an identity function, while the right also evaluates to an identity function.
In general, “observational equivalence” means that the two programs make the same observations; that is, behave exactly identically. For example, in C, two programs would be observationally equivalent if they write to the same memory addresses, return the same values, and print the same results (among other things). In the lambda calculus, however, we only have one notion of observation: whether a given term terminates. Recall from last lecture that the term \( \Omega := (\lambda x. x\ x)\ (\lambda x. x\ x) \) loops forever. Thus, we can craft a term, called poisonPill, that loops forever whenever it is called:
\[ \mathsf{poisonPill} := \lambda z. \Omega \]
Then, to know whether two terms are observationally equivalent, we can ask if they terminate the exact same when given the same arguments. For example, \( \lambda x. x \) and \( (\lambda x. x)\ (\lambda y. y) \) will, both when given A, just return A, even if A loops forever when it is called; thus, they will both always behave the same in all contexts. However, \(\mathsf{LTrue}\) and \(\mathsf{LFalse}\) don’t have the same termination behavior when given the following arguments (abbreviated \( \mathsf{id}\) for \(\lambda x. x\)):
\[ \begin{align*} &(\mathsf{Ltrue}\ \mathsf{poisonPill}\ \mathsf{id})\ \mathsf{id} \\ &(\mathsf{Lfalse}\ \mathsf{poisonPill}\ \mathsf{id})\ \mathsf{id} \end{align*} \]
A more interesting observational equivalence the following one: \(\mathsf{Ltrue}\) is observationally equivalent to \( \lambda z. \mathsf{Ltrue}\ z \). Since everything in the lambda calculus is a function, any function value is equivalent to a function that calls that value on its argument.
However, \( \Omega \) is definitely not observationally equivalent to \( \lambda z. \Omega\ z \)!
Natural Numbers
In addition to Booleans, the lambda calculus can actually represent any inductive datatype that we would want to represent in Lait. As another example, let’s consider the natural numbers. As an inductive datatype, we can represent the natural numbers like so:
type Nat := | NZero | NSucc (val : Nat)
Hence, 0 is represented with NZero, 2 as NSucc (NSucc NZero), and so on.
There are multiple ways of representing these in the lambda calculus.
For our purposes, we will use the Scott encoding. (The other popular encoding is the Church encoding.)
The basic idea of the Scott encoding is that we represent each element of the type Nat above as a function of its constructors. First, let’s see what that looks like in Lait.
def zero := fun z => fun s => z
def succ n := fun z => fun s => s n
Hence, zero, when given arguments for zero and successor, just returns the zero argument. Similarly succ, on a number n, when given arguments for zero and successor,
returns the successor argument applied to n.
Similar to if/then/else, we can think of the arguments to Scott numerals not only as constructors, but also case analysis. Given a Scott number n and two other terms
A and B, the term n A B can be thought of as follows: if n is 0, return A; otherwise, if n is m + 1, return B applied to m.
For example, we can see if a number is positive via case analysis:
def isPos n := n false (fun _ => true)
#eval isPos zero>> false
#eval isPos (succ zero)>> true
Let’s now convert Scott numerals to lambda calculus:
\[ \begin{align*} \mathsf{LZero} :=\ &\lambda z. \lambda s. z \\ \mathsf{LSucc} := \lambda n. &\lambda z. \lambda s. s\ n \end{align*} \]
Hence, we have that 2 = LSucc (LSucc LZero) is represented as \(\lambda z. \lambda s. s (\lambda z. \lambda s. s (\lambda z. \lambda s. z))\).
Addition via Recursion
Note
This is a special topic for the interested reader. The point is that the lambda calculus can embed arbitrary programs.
Now, let’s see how we can define mathematical operations on Scott numerals. We will consider addition. To see how it works, let’s first see how it works on our datatype from earlier:
def add_nat (n1 : Nat) (n2 : Nat) : Nat :=
match n1 with
| NZero => n2
| NSucc n1' => NSucc (add_nat n1' n2)
end
We define addition by recursion on the first number: if n1 is zero, then we return n2; otherwise, n1 = n1' + 1, so we return the successor of n1' + n2.
Thus, there are actually two ingredients that make addition work: case analysis on n1, and recursion.
To make recursion work, one can write a fixpoint combinator in the lambda calculus that lets you write recursive functions.
The idea of a fixpoint combinator is that we can turn a non-recursive function into a recursive one, by having the non-recursive function take an explicit “self” argument.
For example, add_nat could instead be represented as:
fix (fun self n1 n2 =>
match n1 with
| NZero => n2
| NSucc n1' => NSucc (self n1' n2)
end
)
As there are multiple choices of numbers in the lambda calculus, there are also multiple choices of fixpoint combinators. Let’s choose one, called the Z combinator: \[ \mathsf{fix} := \lambda f. (\lambda x. f (\lambda v. x\ x\ v)) (\lambda x. f (\lambda v. x\ x\ v)) \]
We can then define addition as we did in Lait: \[ \mathsf{add} := \mathsf{fix} (\lambda \mathsf{self}. \lambda n_1. \lambda n_2. n_1\ n_2\ (\lambda n_1’. \mathsf{LSucc} (\mathsf{self}\ n_1’\ n_2)) ) \]
Let’s embed these terms into Lait to see that they work:
-- Scott numeral: 0
def Z := ELam "z" (ELam "s" (EVar "z"))
-- Scott numeral: S
def S := ELam "n" (ELam "z" (ELam "s" (EApp (EVar "s") (EVar "n"))))
def One := EApp S Z
def Two := EApp S (EApp S Z)
#eval interp Two>> VLam "z" (ELam "s" (EApp (EVar "s") (ELam "z" (ELam "s" (EApp (EVar "s") (ELam "z" (ELam "s" (EVar "z"))))))))
-- Z combinator
def Fix := ELam "f" (
EApp (
ELam "x" (
EApp (EVar "f") (ELam "v" (EApp (EApp (EVar "x") (EVar "x")) (EVar "v")))
)
)
(
ELam "x" (
EApp (EVar "f") (ELam "v" (EApp (EApp (EVar "x") (EVar "x")) (EVar "v")))
)
)
)
def Add := EApp Fix (ELam "self" (ELam "x" (ELam "y"
(EApp (EApp (EVar "y") (EVar "x")) (ELam "n" (EApp S (EApp (EApp (EVar "self") (EVar "n")) (EVar "x"))))))))
#eval interp (EApp (EApp Add Two) Two)>> VLam "z" (ELam "s" (EApp (EVar "s") (ELam "z" (ELam "s" (EApp (EVar "s") (ELam "z" (ELam "s" (EApp (EVar "s") (ELam "z" (ELam "s" (EApp (EVar "s") (ELam "z" (ELam "s" (EVar "z"))))))))))))))
Real-World Experiments with the Lambda Calculus
The above section shows how the lambda calculus can embed natural numbers. Indeed, by extending these methods, it can actually represent arbitrary computations via simply recursion and “pattern matching” over datatypes, represented through encodings like the Scott numerals. Taken to its logical extreme, one can implement arbitrary programs as lambda calculus terms. For example, here is an entire C compiler written as one gigantic lambda calculus term. This compiler can turn arbitrary C code into lambda calculus terms, and then evaluate them using an interpreter for the lambda calculus (much like what we have in Lait).