PP26  ·  Session 4  ·  lab 4  ·  solutions

An Evaluator for the λ-Calculus — solutions

The five paper exercises reduced step by step, then every hole of lambda.ml filled with the reasoning next to the code. The code without the commentary is about forty lines; the interesting part of each function is which case it is in and what that case decides. The two evaluation strategies are two match functions that differ in one clause each.

00 — how to use these

One file, and a way to read it

lambda.ml is a drop-in replacement for the file with the holes; copy it over ours and dune exec ./main.exe reports 31 passes. It carries more comments than a solution normally would, because the point of each function is why its cases are what they are.

The paper solutions below write one β-step per line and name the redex. Where a definition such as if or succ is unfolded, the line says so; unfolding a name is not a β-step, only a convenience of writing.

A note on notation: λx y. t abbreviates λx. λy. t, and application groups to the left, so f a b is (f a) b.

01 — warm-up, on paper

Five reductions

P1 — ((λx. λy. x y) (λz. z z)) (λw. w)

(λx. λy. x y) (λz. z z) (λw. w)
→ (λy. (λz. z z) y) (λw. w)        x := λz. z z
→ (λz. z z) (λw. w)                y := λw. w
→ (λw. w) (λw. w)                  z := λw. w
→ λw. w                            w := λw. w

Four β-steps; the normal form is the identity. Every step here reduces the leftmost-outermost redex. After the first step there is a second one, inside the λy: applicative order would take it and reach (λy. y y) (λw. w) — the same normal form by another path.

P2 — (λx. λy. x y) y

In λx. λy. x y, x and y are bound. In the whole term, the argument y is free — it is a different y from the bound one, which only happens to have the same name.

Substituting naively gives λy. y y: the free y has fallen under the λy and is now bound — captured; the term no longer mentions the outer y at all. So the binder is renamed first:

(λx. λy. x y) y  =  (λx. λy'. x y') y      α: y → y' inside the function
→ λy'. y y'                                 x := y

The normal form is λy'. y y', with the left y still free. Whether we write y', z or w for the renamed binder does not matter: terms that differ only in the names of bound variables are the same term.

P3 — (λx. I) Ω, two orders

With I = λz. z and Ω = (λu. u u) (λu. u u). The term has two redexes: the outer application, and Ω itself inside the argument.

Normal order (leftmost-outermost first): the outer redex is (λx. I) Ω; x does not occur in I, so the argument is thrown away.

(λx. I) Ω
→ I  =  λz. z                     x := Ω, and x is not used

Applicative order (leftmost-innermost first): the innermost redex is Ω, so it must be reduced before the outer application — and Ω reduces to itself.

(λx. I) ((λu. u u) (λu. u u))
→ (λx. I) ((λu. u u) (λu. u u))   u := λu. u u  — the same term
→ (λx. I) ((λu. u u) (λu. u u))
→ …                                forever

Why: normal order never evaluates an argument that is not used; applicative order evaluates every argument, used or not. A normal form exists (λz. z) and normal order finds it; applicative order never reaches it. This is the lecture's Does the order matter?, on paper.

P4 — if true a b and if false a b

Unfold if = λc. λt. λe. c t e and true = λt. λf. t:

(λc. λt. λe. c t e) true a b
→ (λt. λe. true t e) a b           c := true
→ (λe. true a e) b                 t := a
→ true a b                         e := b
=  (λt. λf. t) a b                 unfold true
→ (λf. a) b                        t := a
→ a                                f := b

With false = λt. λf. f the last two steps give (λf. f) b → b. So if does nothing but pass the two branches to the boolean, and the boolean is the one that chooses: a boolean is a two-way choice.

P5 — succ 1

Unfold succ = λn. λf. λx. f (n f x) and 1 = λf. λx. f x:

(λn. λf. λx. f (n f x)) (λf. λx. f x)
→ λf. λx. f ((λf. λx. f x) f x)     n := 1
→ λf. λx. f ((λx. f x) x)           the inner f := f
→ λf. λx. f (f x)                   the inner x := x

The normal form is λf. λx. f (f x): f applied twice, which is the numeral 2. Note that the last two steps reduce inside a λ; a weak strategy — the one real languages use — would stop after the first step and leave λf. λx. f ((λf. λx. f x) f x), which is 2 too, only not yet written out.

02 — warm-up, in code

The term as data

W1 — size

let rec size = function
  | Var _ -> 1
  | Lam (_, t) -> 1 + size t
  | App (f, a) -> 1 + size f + size a

One case per constructor, one recursive call per sub-term — the shape of every function on this type, and the same shape as count_notes on session 3's melody tree.

W2 — free_vars

let rec free_vars t =
  let fv = match t with
    | Var x -> [x]
    | Lam (x, b) -> List.filter (fun y -> y <> x) (free_vars b)
    | App (f, a) -> free_vars f @ free_vars a
  in List.sort_uniq compare fv

The three equations of the lecture, line for line: a variable is free in itself; a λ removes its own variable from the free variables of its body; an application collects both sides. sort_uniq at the end makes the result a set, so x (λx. x) gives [x] — the first x is free although the second is bound.

W3 — is_closed

let is_closed t = free_vars t = []

W4 — subst

let rec subst t x u =
  match t with
  | Var y -> if y = x then u else t
  | App (f, a) -> App (subst f x u, subst a x u)
  | Lam (y, b) ->
      if y = x then t
      else if List.mem y (free_vars u) && List.mem x (free_vars b) then
        let y' = fresh y (free_vars u @ free_vars b) in
        Lam (y', subst (subst b y (Var y')) x u)
      else Lam (y, subst b x u)

The Lam case has three outcomes, and the order of the tests matters.

  • y = x: the λ binds the very variable we are replacing, so nothing inside it is a free x. Return the term unchanged — (λx. x)[x := y] is λx. x.
  • y is free in u and x is free in b: putting u into b would place a free y under this λy — capture. Pick a name y' that is free in neither u nor b — fresh y (free_vars u @ free_vars b), provided just above subst, adds primes to y until the name is in neither list — rename the binder (subst b y (Var y') is safe: y' is fresh, so it cannot itself be captured), then substitute.
  • otherwise: substitute in the body and keep the binder. This includes the case where y is free in u but x does not occur in b at all — then nothing is substituted, so nothing can be captured, and renaming would be needless. That is what the check (λy. x y)[x := λz. z] tests: z is bound in u, not free, so no renaming.

Renaming eagerly (whenever y is free in u) is also correct, only noisier. Renaming never — the "first attempt" of most people — produces λy. y for (λy. x)[x := y], and the check catches it.

03 — part A

Small-step evaluation: three strategies, one clause apart

A1 — call by name, weak

let rec step_cbn = function
  | App (Lam (x, b), a) -> Some (subst b x a)
  | App (f, a) -> (match step_cbn f with Some f' -> Some (App (f', a)) | None -> None)
  | _ -> None

Two rules, as on the lecture's Small-step operational semantics: the rules: if the function part is a λ, β — the argument goes in unevaluated; otherwise step in the function part. A Var or a Lam steps nowhere: weak reduction never enters a λ, and never touches the argument of an application.

A2 — call by value, weak

let rec step_cbv = function
  | App (f, a) when not (is_value f) ->
      (match step_cbv f with Some f' -> Some (App (f', a)) | None -> None)
  | App (f, a) when not (is_value a) ->
      (match step_cbv a with Some a' -> Some (App (f, a')) | None -> None)
  | App (Lam (x, b), a) -> Some (subst b x a)
  | _ -> None

The two when guards are the premises of the two congruence rules: the function part must be a value before the argument is looked at, and the argument must be a value before β fires. That is the whole difference from A1 — one extra clause, the second one — and it is what makes (λx. λy. y) Ω loop: Ω is the argument, it is not a value, so step_cbv keeps stepping it, and it steps to itself.

The two strategies part company on the first step of (λx. x) ((λy. y) z): call by name reduces the outer redex first, (λy. y) z; call by value the inner one, (λx. x) z. Both reach z.

A3 — normal order, full

let rec step_normal = function
  | App (Lam (x, b), a) -> Some (subst b x a)
  | App (f, a) ->
      (match step_normal f with
       | Some f' -> Some (App (f', a))
       | None -> (match step_normal a with Some a' -> Some (App (f, a')) | None -> None))
  | Lam (x, b) -> (match step_normal b with Some b' -> Some (Lam (x, b')) | None -> None)
  | Var _ -> None

Call by name plus two clauses: when the function part is stuck, step in the argument; and step inside a λ. This is the strategy of the paper exercises — it reduces everywhere, leftmost-outermost first — and the one that finds a normal form whenever there is one. It is what normalize uses to turn add 2 1 into λf x. f (f (f x)), which church_to_int reads as 3; Y fact 3 reaches 6 in about two thousand steps, most of them spent inside pred.

04 — part B

Big-step evaluation: environments and closures

B1 — eval

let rec eval env = function
  | Var x -> (match List.assoc_opt x env with Some v -> v | None -> failwith ("unbound variable " ^ x))
  | Lam (x, b) -> Closure (x, b, env)
  | App (f, a) ->
      let Closure (x, b, env') = eval env f in
      let v = eval env a in
      eval ((x, v) :: env') b

No substitution anywhere. A variable is looked up; a λ is not run but packaged with the environment it was made in; an application evaluates the function to a closure, the argument to a value (call by value: the argument before the body, always), and then the closure's body in the closure's own environment env', extended with the parameter.

The third check is the one that tells env' from env: in (λx. (λf. (λx. f x) (λw. w)) (λy. x)) (λz. z) the inner function λy. x is made where x is λz. z but called where x is λw. w. Using the caller's environment gives the wrong answer; that mistake has a name, dynamic scope, as in the early Lisps; a closure is how lexical scope is implemented.

So the answer to the lab's closing question: a closure carries the bindings of the free variables of its body, as they were when the λ was evaluated. Session 5 starts from this: a closure with a mutable binding inside is an object.

B2 — readback

let rec readback (Closure (x, b, env)) =
  Lam (x, List.fold_left (fun t (y, v) -> if y = x then t else subst t y (readback v)) b env)

The inverse move: put the environment back into the body, one binding at a time, each value read back into a term first. The one subtlety is if y = x then t: a binding of the closure's own parameter in env is shadowed by the λx and must be skipped, or an old x would be substituted into a body where x means the parameter. Because every closure comes from a closed program, the read-back terms are closed, and subst never has to rename.

With it, normalize (readback (eval [] (parse "add 2 1"))) is the numeral 3, and Z factv 3 evaluates to 6 — through closures, without a single substitution during evaluation. Z fact 3 does not stop: eval is call by value, and fact's two branches are both arguments of if.

05 — the extensions

Hints, not solutions

  • Church arithmetic. exp = λm n. n m (apply "times m" n times); iszero = λn. n (λx. false) true. pred is long because a numeral can only count up: it counts from (0, 0) through pairs (k, k+1) and keeps the first component.
  • Y and Z. Under call by value Y g steps (λx. g (x x)) (λx. g (x x)) to g ((λx. g (x x)) (λx. g (x x))), whose argument is the same redex again: the trace repeats with one more g each time. Z puts a λv. in front of x x, so it is a value and the trace stops there — but fact's branches are still both evaluated, hence factv.
  • Full normalisation under call by value. Once step_cbv returns None on Lam (x, b), continue with b. The two normalisers agree whenever both terminate; they differ on terms like (λx. λy. y) Ω, where only the normal-order one does.
  • De Bruijn indices. Lam of term with no name and Var of int; substitution becomes shifting of indices and needs no fresh. The conversion from named terms carries a list of the binders in scope.
  • A small ML. Add Int, Add, If, Let to term and VInt to value; If must evaluate only one branch — it is the one place where the evaluator decides not to be call by value. This is the program session 10 gives a type checker.
  • Meta-circular. VFun of (value -> value): eval env (Lam (x, b)) = VFun (fun v -> eval ((x, v) :: env) b). What is lost is readback: an OCaml function cannot be inspected, only called — session 3's Way 2, exactly.