PP26  ·  Session 4  ·  lab

An Evaluator for the λ-Calculus

We write the λ-calculus as an OCaml type and then the programs that run it: substitution, two evaluation strategies step by step, and a big-step evaluator whose function values are closures. The lecture said that a language decides when an argument is evaluated; here we make that decision ourselves, twice, and watch Ω go one way under one strategy and the other way under the other.

00 — description

What this lab is for

Block 2 of the lecture defined the calculus in three forms and one rule, and showed that the order in which the rule is applied is a design decision: normal order and applicative order reach the same answer when both reach one, and only one of them reaches an answer for (λx. λy. y) Ω. The lab makes both orders into code, on the same fifteen-line type, and then does what a language does instead of substituting: keeps an environment and makes closures.

The lab has two halves. The warm-up is five paper exercises and four small functions on the term type; it is meant to be finished in the lab. The main lab (Parts A and B) is started in the lab and finished during the week. Nothing is handed in.

dune build
dune exec ./main.exe        # pass / FAIL / todo, one line per check

Each hole in lambda.ml is a failwith "TODO …"; main.ml reports it as todo until it is filled, then as pass or FAIL. Terms can be tried by hand in dune utop, once W4 is done: trace CBN 20 (Syntax.parse "(λx. λy. y) Ω") — in plain ocaml, first #mod_use "term.ml";; #mod_use "syntax.ml";; #use "lambda.ml";;.

01 — the type

The calculus, as a type

type term =
  | Var of string                 (* x        *)
  | Lam of string * term          (* λx. t    *)
  | App of term * term            (* t u      *)

Provided

  • pretty : term -> string prints λx y. t with the fewest parentheses.
  • Syntax.parse : string -> term reads "(λx. λy. x y) (λz. z z)"; a backslash works for λ, and λx y. t abbreviates λx. λy. t.
  • The lecture's definitions by name — true, if, succ, add, mul, pred, Y, Z, Ω, fact, factv — and digits as Church numerals.
  • church_to_int : term -> int option reads a numeral back.

Every function in the lab is one match on this type — session 3's thesis on a type with three shapes. Its values are trees, and a step of evaluation builds a new tree, sharing what it did not change.

02 — warm-up

On paper, then in codewarm-up

The sheet to print: lambda-on-paper.pdf. Reduce by hand, one β-step per line, marking the redex reduced at each step.

P1((λx. λy. x y) (λz. z z)) (λw. w) — to normal form.
P2(λx. λy. x y) y — which variables are free, which are bound? Reduce without capturing the free y.
P3Let I = λz. z and Ω = (λu. u u) (λu. u u). Reduce (λx. I) Ω in normal order (leftmost-outermost redex first). Then start it in applicative order (leftmost-innermost). What happens in each case, and why?
P4if true a b with true = λt. λf. t and if = λc. λt. λe. c t e — to normal form. Then if false a b.
P5succ 1 with succ = λn. λf. λx. f (n f x) and 1 = λf. λx. f x — to normal form. Which numeral is it?

In code

W1The size of a term: the number of constructors in it.
size : term -> int
W2The free variables, sorted and without duplicates. A Lam removes its own variable from the free variables of its body. x (λx. x) has x free: the same name can be bound in one place and free in another.
free_vars : term -> string list
W3A term is closed when it has no free variable.
is_closed : term -> bool
W4Substitution, subst t x u: t with u put in for every free occurrence of x. The Var and App cases are done, and so is the Lam case that binds x itself. The hole is Lam (y, b) for y ≠ x, with two sub-cases: if y is not free in u (or x not free in b), substitute in the body; otherwise a free y of u would be captured — rename the binder first, then substitute. fresh y avoid, provided just above subst, returns y with primes added until it is not in the list avoid: fresh "y" ["y"; "y'"] is "y''". (λy. x)[x := y] must give λy'. y; (λy. x y)[x := λz. z] must rename nothing. The lecture's Substitution and capture, and the lab's hardest twenty lines.
subst : term -> string -> term -> term

03 — the main lab

Two evaluatorsassignment

Part A — small-step evaluation

A step function returns the term after one β-reduction, or None when there is none to do under its strategy. trace strategy cap t, provided, applies it repeatedly and returns the terms reached and whether a normal form was reached before cap steps; result returns only the final term.

A1Call-by-name, weak. If the function part is a λ, reduce the redex; otherwise step in the function part. Never step into the argument, never inside a λ.
step_cbn : term -> term option
A2Call-by-value, weak. The function part first, until it is a value; then the argument, until it is a value; then the redex. is_value is provided: a λ is a value, an application is not — and so is a free variable such as a, which cannot be reduced, so call by value must treat it as done; that is what lets the checks use a and b as placeholders. Now run both on (λx. λy. y) Ω: call-by-name reaches λy. y in one step; call-by-value never finishes — it is reducing Ω to Ω, exactly as on paper in P3.
step_cbv : term -> term option
A3Normal order, full: the leftmost-outermost redex anywhere, inside a λ too. This is the strategy of the paper exercises. With it, normalize (provided) turns add 2 1 into the numeral λf x. f (f (f x)), and Y fact 3 reaches 6 in about two thousand steps.
step_normal : term -> term option

Part B — big-step evaluation with environments

Substituting at every step is what the calculus does; it is not what a language does. A language keeps the argument in an environment and looks a variable up when it meets it. A function value then has to carry the environment it was made in — it is a closure:

type value = Closure of string * term * env
and env = (string * value) list
B1eval env t under call-by-value. A variable is looked up (done); a λ becomes a closure over the current environment; an application evaluates the function to a closure, the argument to a value, and the closure's body in the closure's environment extended with the parameter, added at the front of the list — the closure's environment, not the caller's. eval is for closed terms; a free variable raises unbound variable. The third check tells the two apart. Then look at eval [] (Syntax.parse "(λx. λy. x) (λz. z)"): a closure whose environment holds x. What does the closure carry? is session 5's first question.
eval : env -> term -> value
B2readback: a closure back into a term, by substituting every binding of its environment into its body. One trap: a binding of the closure's own parameter may sit in the environment; it is shadowed by the λ and must be skipped. Then add 2 1 evaluates to the numeral 3, and Z factv 3 — the lecture's call-by-value factorial, whose branches are delayed — to 6. Try Z fact 3, whose branches are not, and stop it with Ctrl-C.
readback : value -> term

04 — homework

What to finish at home, and where to go onassignment

  • Finish the parts left open; the checks say which.
  • Church arithmetic as terms. Write exp and iszero as strings and check them with normalize. Why is pred so much longer than succ?
  • Y and Z in our own evaluator. Y fact 3 under Normal reaches 6; under CBV it does not — explain from the trace where it loops. Then Z fact 3 under CBV: still no; explain why factv is needed as well.
  • Full normalisation under call-by-value. Once weak reduction stops at λx. b, continue inside b. When do the two normalisers agree?
  • De Bruijn indices. Replace names by the number of λs between a variable and its binder: λx. λy. x becomes λ. λ. 1. Substitution needs no renaming any more.
  • A small ML. Add Int, Add, If and Let to the type and extend eval. The evaluator is now a language; session 10 gives it a type checker. A seed for a mini-project.
  • A meta-circular evaluator. Replace Closure by VFun of (value -> value): a λ becomes an OCaml function — the constructor carrying a function that session 3 promised. What did we lose?
  • Reading. CS3110, chapter 10, sections 10.1–10.4; Pierce, Types and Programming Languages, chapter 5, for the paper exercises.