HW3
Due Date: Friday, Oct 23, 11:59pm
- Upload your submission to Gradescope, starting from this starter code.
You should upload only a single Lean file beginning with the following two lines:
import Lait
#lait
-
Be sure to check that your submission is valid Lait code that type checks; if it is not, you will receive 0 points for that problem.
-
Your programs will be evaluated based on a number of tests. Gradescope will show you some tests when you submit, but not all of them. However, all of the tests we run will be testing the program’s specification, which will be unambiguous. You should test your code thoroughly before submitting.
-
For each problem, you should include at least 3 passing test cases different than the ones given below.
1. Environments (40 points)
In Lecture 3, we gave a semantics to LetLang using substitution: to evaluate let x := e1 in e2, we evaluate e1 to a value v, and then substitute v for x everywhere in e2.
Substitution is an elegant way of describing semantics, but its implementation can be quite slow: every substitution has to scan over (and rebuild) the whole body of the let, which does not scale in practice.
Instead, most real interpreters use an environment: a map that records the value of every variable that is currently in scope. Rather than substituting, the interpreter carries the environment along as it runs:
- To evaluate a variable
x, look upxin the environment. - To evaluate
let x := e1 in e2, evaluatee1to a valuev, and then evaluatee2in the environment extended withx ↦ v.
For example, here is how let x := 10 in let y := x + 1 in x + y evaluates, starting from the empty environment {}:
evaluate let x := 10 in let y := x + 1 in x + y in {}
evaluate 10 in {} ==> 10
evaluate let y := x + 1 in x + y in {x ↦ 10}
evaluate x + 1 in {x ↦ 10} ==> 11
evaluate x + y in {x ↦ 10, y ↦ 11} ==> 21
We will use the following abstract syntax for LetLang:
type LetExpr :=
| NumL (n : Int)
| AddL (l : LetExpr) (r : LetExpr)
| MulL (l : LetExpr) (r : LetExpr)
| VarL (s : String)
| LetL (var : String) (assignment : LetExpr) (body : LetExpr)
We will represent environments using Lait’s built-in Map type, which supports Map.empty, Map.lookup, and Map.insert.
You can find more information about maps in the Lait book.
Implement a definitional interpreter interpLetEnv that uses a map to store the values of variables:
def interpLetEnv (env : Map<String, Int>) (e : LetExpr) : Int := ...
This function should not use substitution. Your interpreter should behave identically to the usual substitution semantics for LetLang, and in particular must respect lexical scope (including shadowing) as described in Lecture 3.
If you encounter a variable that is not in the environment, raise an error using error.
Example tests:
#test interpLetEnv Map.empty (LetL "x" (NumL 10)
(AddL (VarL "x") (VarL "x")))
=== 20
#test interpLetEnv (Map.insert Map.empty "y" 20) (LetL "x" (NumL 10)
(AddL (VarL "y") (VarL "x")))
=== 30
2. Working with Church Numerals (60 points)
In Lecture 5, we briefly discussed the Scott numerals, a way to encode natural numbers into the Lambda Calculus. In this problem, we will explore the other main way of encoding numbers: Church numerals.
For this problem, we will work with the following data structure for the lambda calculus:
type Lam :=
| VarE (id : String)
| LamE (arg : String) (body : Lam)
| AppE (e1 : Lam) (e2 : Lam)
The idea of the Church numerals is, like the Church booleans, to represent a number by its behavior. What is the behavior of a given number (say, 3)? We will say it is to repeat an action that many times.
Hence, the Church numeral for n is the function that takes a function f and a starting point x, and applies f to x, n times:
\[ \begin{aligned} 0 &:= \lambda f. \lambda x. x \\ 1 &:= \lambda f. \lambda x. f\ x \\ 2 &:= \lambda f. \lambda x. f\ (f\ x) \\ 3 &:= \lambda f. \lambda x. f\ (f\ (f\ x)) \\ &\ \ \vdots \end{aligned} \]
Instead of writing each number by hand, observe that we can use the following function, succ, to increment a Church numeral by one:
\[
\mathsf{succ} := \lambda n. \lambda f. \lambda x. f\ (n\ f\ x)
\]
Above, succ takes a Church numeral n and makes a new Church numeral by taking f and x, and applies f to the result of n f x. Hence, if n f x applies f to x N many times, then succ n will apply f to x N+1 many times.
Given succ, we can then write 1 := succ 0, 2 := succ 1, and so on.
Before working directly with the lambda calculus, let’s see that we can encode this in Lait.
def zero := fun f => fun x => x
def succ := fun n => fun f => fun x => f (n f x)
-- For technical Lait-only reasons, we need to unfold the definition
-- of `succ` above in the below two definitions.
-- one = succ zero
def one := fun f => fun x => f (zero f x)
-- two = succ one
def two := fun f => fun x => f (one f x)
#eval two (fun x => x ++ "!") "hi">> "hi!!"
Above, we get "hi!!" out, because we iterated fun x => x ++ "!" twice on the initial input, "hi".
In this problem, you will implement operations on the Church numerals in the lambda calculus. To help you out, we have given you in the starter code a function Church.decode : Lam -> Int, which can decode Church numerals into integers. The Church.decode function also runs the lambda term, so you can feel free to pass applications into it.
-- zero = λf. λx. x
def Church.zero : Lam := LamE "f" (LamE "x" (VarE "x"))
-- succ = λn. λf. λx. f (n f x)
def Church.succ : Lam :=
LamE "n" (LamE "f" (LamE "x"
(AppE (VarE "f") (AppE (AppE (VarE "n") (VarE "f")) (VarE "x")))))
def Church.one := AppE Church.succ Church.zero
def Church.two := AppE Church.succ Church.one
def Church.three := AppE Church.succ Church.two
-- Problem 2.1
def Church.ofInt (n : Int) : Lam :=
if n < 0 then error "Church.ofInt negative number"
else ...
First, given a non-negative number, implement a function Church.ofInt that turns that number into a Church numeral. The implementation should recurse on the given number, n,
using Church.zero in the base case, and using Church.succ in the recursive case.
Next, we are going to implement variants of addition and multiplication that work over Church numerals.
-- Problem 2.2
def Church.add : Lam := LamE "n" (LamE "m" ...)
-- Problem 2.3
def Church.mul : Lam := LamE "n" (LamE "m" ...)
Both solutions for Church.add and Church.mul will take in Church numerals for n and m, and output a new Church numeral.
To implement Church.add, we will follow the intuition of Church numerals: we take in a function f, an argument x, and apply f to x that numeral amount of times.
This gives us a straightforward way to implement addition: to add n to m, we can increment m by one (using Church.succ) n number of times.
That is, in symbols:
\[ n + m = m\ \underbrace{+\ 1 + 1 + \dots + 1}_{n \text{ times}} \]
Once you have Church.add, implementing Church.mul is similar, since n times m is the same as adding m to zero, n number of times:
\[ n \cdot m = 0\ \underbrace{+\ m + m + \dots + m}_{n \text{ times}} \]
Compiling LetExpr into the lambda calculus
Now, we are going to use Church numerals to compile LetExpr from the first problem into the lambda calculus:
-- Problem 2.4
def LetExpr.toLam (e : LetExpr) : Lam := ...
Your compiler must be correct, the following sense: if we have a closed LetExpr program p which does not contain negative numbers, then evaluating p under the ordinary semantics should be equivalent to running Church.decode on LetExpr.toLam p:
forall p, interpLetEnv Map.empty p = Church.decode (LetExpr.toLam p)
Hence, you may assume for this problem that all arguments to NumL inside of the LetExpr program e are nonnegative.
To implement LetExpr.toLam, note that LetExpr contains two language features: numbers, and let bindings. For numbers, you need to use Church numerals. For let bindings, you will need to find a way to encode let x = e1 in e2 using the (minimal) features of the lambda calculus.
To evaluate the correctness of your compiler, you should write a variety of tests, using #test, of the above property. For example:
def myProg : LetExpr := LetL "x" (NumL 10) (MulL (VarL "x") (NumL 2))
#test interpLetEnv Map.empty myProg === Church.decode (LetExpr.toLam myProg)
Note that Lait has a default step limit, and the implementation of Church.mul we guide you towards in this homework is quite inefficient; hence, multiplications of larger numbers (e.g., 5 * 8) will hit the step counter. Your tests can be over small numbers, as long as they are correct.
(There is a faster implementation of Church.mul that allows you to evaluate larger multiplications, such as 10 * 8, without hitting the step limit. Feel free to look for the faster verison as well!)