Programming Paradigms · session 11 · Polymorphism · quest

Quest: algorithm W

Lab Session: Algorithm W (by Jean-Christophe Filliatre)

The goal of this tutorial is to implement algorithm W for mini-ML. We will consider a version with destructive unification.

Files and Playground

The quest starts from w.ml: the types and the code that the statement gives, a hole for each definition to write, and the tests. A hole is the expression failwith "TODO". Two files hold the solution: w_solutions.ml, and w_solutions_commented.ml, the same code with comments on each definition.

The OCaml Playground of ocaml.org is a toplevel that runs in the browser, with nothing to install. The button below docks it on the lower half of the window; its bar has two rows of tabs.

Beside the statement, the right column holds notes that are not from the source page, each folded under its title: a Concept, a Notion or a Definition recalls a point of OCaml or of the code that the statement uses, most with a short program; a Hint gives an idea of the algorithm, and so part of an answer.

The upper edge of the dock is a handle: dragging it sets the height. The button Right side moves the dock to the right of the window, where its left edge sets the width; Bottom brings it back.

The Run button of the Playground evaluates what its editor holds. With a hole left, a test ends on Exception: Failure "TODO".; with the holes filled, the tests of the source print nothing, and the additional tests print the types they compute, then a line that says they passed. Nothing is loaded from ocaml.org before a button is pressed.

On a machine with OCaml, ocaml w.ml runs the file in a terminal. The outputs on this page come from OCaml 5.4.0; the files use the standard library only.

Types and type variables

We start by introducing the abstract syntax of types.

type typ =
  | Tint
  | Tarrow of typ * typ
  | Tproduct of typ * typ
  | Tvar of tvar

and tvar =
  { id : int;
    mutable def : typ option }

The type typ of mini-ML types is mutually recursive with the type tvar of type variables. Indeed, a type variable contains a possible definition (obtained during unification), which is itself a type. Thus { id = 1; def = None } is "still" a type variable, whereas { id = 2; def = Some Tint } is a former type variable that has been defined to be equal to the type Tint and must now be treated exactly as if it were the type Tint.

To test, we can use the following pretty-printing function:

let rec pp_typ fmt t = match t with
  | Tproduct (t1, t2) -> Format.fprintf fmt "%a *@ %a" pp_atom t1 pp_atom t2
  | Tarrow (t1, t2) -> Format.fprintf fmt "%a ->@ %a" pp_atom t1 pp_typ t2
  | (Tint | Tvar _) as t -> pp_atom fmt t
and pp_atom fmt t = match t with
  | Tint -> Format.fprintf fmt "int"
  | Tvar v -> pp_tvar fmt v
  | Tarrow _ | Tproduct _ as t -> Format.fprintf fmt "@[<1>(%a)@]" pp_typ t
and pp_tvar fmt v = match v with
  | { def = None; id } -> Format.fprintf fmt "'%d" id
  | { def = Some t; id } -> Format.fprintf fmt "@[<1>('%d := %a)@]" id pp_typ t

We then introduce a module V encapsulating the type tvar with a comparison function and a function that creates a fresh type variable.

module V = struct
  type t = tvar
  let compare v1 v2 = Stdlib.compare v1.id v2.id
  let equal v1 v2 = v1.id = v2.id
  let create = let r = ref 0 in fun () -> incr r; { id = !r; def = None }
end

Question 1. Normalization

To make handling type variables easier, we introduce two functions that normalize a type expression by following the definitions contained in type variables.

Write a function

val head : typ -> typ

that normalizes a type at the head, i.e., head t returns a type equal to t that is not of the form Tvar { def = Some _}. In other words, head t follows type-variable definitions at the head of t for as long as there are any.

Write a function

val canon : typ -> typ

that completely normalizes a type, i.e., that applies the function head above recursively. This second function will be used only for printing types (in the result of a typing operation or in error messages).

We can test with

let () =
  let a = V.create () in
  let b = V.create () in
  let ta = Tvar a in
  let tb = Tvar b in
  assert (head ta == ta);
  assert (head tb == tb);
  let ty = Tarrow (ta, tb) in
  a.def <- Some tb;
  assert (head ta == tb);
  assert (head tb == tb);
  b.def <- Some Tint;
  assert (head ta = Tint);
  assert (head tb = Tint);
  assert (canon ta = Tint);
  assert (canon tb = Tint);
  assert (canon ty = Tarrow (Tint, Tint))

The tab of this question in the Playground ends with additional tests, which are not from the source page:

Additional tests of question 1
let () =
  let a = V.create () in
  let b = V.create () in
  let ty = Tarrow (Tvar a, Tproduct (Tvar a, Tvar b)) in
  Format.printf "@[<h>a type with two variables:  %a@]@." pp_typ ty;
  a.def <- Some Tint;
  Format.printf "@[<h>after  a.def <- Some Tint:  %a@]@." pp_typ ty;
  Format.printf "@[<h>the same type by canon:     %a@]@." pp_typ (canon ty);
  (* head looks at the root only: the root of ty is an arrow, and head
     returns ty itself, with the defined variable still under it *)
  assert (head ty == ty);
  (* canon goes under the arrow and the product *)
  assert (match canon ty with
    | Tarrow (Tint, Tproduct (Tint, Tvar v)) -> V.equal v b
    | _ -> false);
  (* a chain of definitions, c := b and b := int, is followed to its end *)
  let c = V.create () in
  c.def <- Some (Tvar b);
  b.def <- Some Tint;
  assert (head (Tvar c) = Tint);
  assert (canon ty = Tarrow (Tint, Tproduct (Tint, Tint)));
  Format.printf "Question 1: additional tests passed@."
Solution of question 1
w_solutions_commented.ml, question 1
(* Question 1. Normalization *)

(* head follows the definitions of variables at the root of a type, as
   long as there is one. The pattern  Tvar { def = Some t }  matches a
   defined variable, whatever its id (a record pattern may leave fields
   out). The result is never a defined variable: it is Tint, an arrow, a
   product or an undefined variable. The functions of the algorithm
   (occur, unify, fvars, find) call head before they look at the shape of
   a type; the printers do not, and show a defined variable as it is. *)
let rec head t = match t with
  | Tvar { def = Some t } -> head t
  | t -> t

(* canon applies head at every level, and returns a type without any
   defined variable. In  Tvar _ | Tint as t  the name t stands for the
   whole value matched by either pattern. canon serves to print a type
   and to compare it in the tests. *)
let rec canon t = match head t with
  | Tvar _ | Tint as t -> t
  | Tarrow (t1, t2) -> Tarrow (canon t1, canon t2)
  | Tproduct (t1, t2) -> Tproduct (canon t1, canon t2)

(* tests *)
(* Three mutually recursive printers, for the module Format: the
   directive %a takes a printer and a value. A defined variable is printed
   with its definition, ('1 := int). *)
let rec pp_typ fmt t = match t with
  | Tproduct (t1, t2) -> Format.fprintf fmt "%a *@ %a" pp_atom t1 pp_atom t2
  | Tarrow (t1, t2) -> Format.fprintf fmt "%a ->@ %a" pp_atom t1 pp_typ t2
  | (Tint | Tvar _) as t -> pp_atom fmt t
and pp_atom fmt t = match t with
  | Tint -> Format.fprintf fmt "int"
  | Tvar v -> pp_tvar fmt v
  | Tarrow _ | Tproduct _ as t -> Format.fprintf fmt "@[<1>(%a)@]" pp_typ t
and pp_tvar fmt v = match v with
  | { def = None; id } -> Format.fprintf fmt "'%d" id
  | { def = Some t; id } -> Format.fprintf fmt "@[<1>('%d := %a)@]" id pp_typ t

(* The test defines a and b by hand, as unification will: after
   a.def <- Some tb  the variable a stands for b, and after
   b.def <- Some Tint  both stand for int. The type ty was built before
   the two assignments, and canon ty still sees them: the definitions are
   in the variables, which ty shares. *)
let () =
  let a = V.create () in
  let b = V.create () in
  let ta = Tvar a in
  let tb = Tvar b in
  assert (head ta == ta);
  assert (head tb == tb);
  let ty = Tarrow (ta, tb) in
  a.def <- Some tb;
  assert (head ta == tb);
  assert (head tb == tb);
  b.def <- Some Tint;
  assert (head ta = Tint);
  assert (head tb = Tint);
  assert (canon ta = Tint);
  assert (canon tb = Tint);
  assert (canon ty = Tarrow (Tint, Tint))
Answers of the toplevel to these definitions
type typ = Tint | Tarrow of typ * typ | Tproduct of typ * typ | Tvar of tvar
and tvar = { id : int; mutable def : typ option; }
module V :
  sig
    type t = tvar
    val compare : tvar -> tvar -> int
    val equal : tvar -> tvar -> bool
    val create : unit -> tvar
  end
val head : typ -> typ = <fun>
val canon : typ -> typ = <fun>
val pp_typ : Format.formatter -> typ -> unit = <fun>
val pp_atom : Format.formatter -> typ -> unit = <fun>
val pp_tvar : Format.formatter -> tvar -> unit = <fun>
Output of the additional tests, with this solution
a type with two variables:  '3 -> '3 * '4
after  a.def <- Some Tint:  ('3 := int) -> ('3 := int) * '4
the same type by canon:     int -> int * '4
Question 1: additional tests passed

Question 2. Unification

To report unification errors, we use the following exception and function:

exception UnificationFailure of typ * typ

let unification_error t1 t2 = raise (UnificationFailure (canon t1, canon t2))

Write a function

val occur : tvar -> typ -> bool

that tests whether a type variable occurs in a type (occur-check). We may assume that the variable itself is undefined. The type, however, may contain defined variables, and head should be applied to it before inspecting it.

Write a function

val unify : typ -> typ -> unit

performing the unification of two types. Again, head should be used on the argument types before they are inspected.

We can test with

let () =
  let a = V.create () in
  let b = V.create () in
  let ta = Tvar a in
  let tb = Tvar b in
  assert (occur a ta);
  assert (occur b tb);
  assert (not (occur a tb));
  let ty = Tarrow (ta, tb) in
  assert (occur a ty);
  assert (occur b ty);
  (* unifies 'a-> 'b and int->int *)
  unify ty (Tarrow (Tint, Tint));
  assert (canon ta = Tint);
  assert (canon ty = Tarrow (Tint, Tint));
  (* unifies 'c and int->int *)
  let c = V.create () in
  let tc = Tvar c in
  unify tc ty;
  assert (canon tc = Tarrow (Tint, Tint))

let cant_unify ty1 ty2 =
  try let _ = unify ty1 ty2 in false with UnificationFailure _ -> true

let () =
  assert (cant_unify Tint (Tarrow (Tint, Tint)));
  assert (cant_unify Tint (Tproduct (Tint, Tint)));
  let a = V.create () in
  let ta = Tvar a in
  unify ta (Tarrow (Tint, Tint));
  assert (cant_unify ta Tint)

The tab of this question in the Playground ends with additional tests, which are not from the source page:

Additional tests of question 2
let () =
  (* each side defines a variable of the other *)
  let a = V.create () in
  let b = V.create () in
  let t1 = Tarrow (Tvar a, Tint) in
  let t2 = Tarrow (Tproduct (Tint, Tvar b), Tvar b) in
  Format.printf "@[<h>unify   %a@]@.@[<h>with    %a@]@." pp_typ t1 pp_typ t2;
  unify t1 t2;
  Format.printf "@[<h>gives   %a@]@." pp_typ (canon t1);
  assert (canon t1 = Tarrow (Tproduct (Tint, Tint), Tint));
  assert (canon t2 = canon t1);
  (* the occur check: 'c against 'c -> int fails, and defines nothing *)
  let c = V.create () in
  assert (cant_unify (Tvar c) (Tarrow (Tvar c, Tint)));
  assert (c.def = None);
  (* a variable against itself: nothing to do, and no definition 'c := 'c *)
  unify (Tvar c) (Tvar c);
  assert (c.def = None);
  (* the variable on the right *)
  let d = V.create () in
  unify Tint (Tvar d);
  assert (canon (Tvar d) = Tint);
  (* two variables: one stands for the other, and defining one then
     defines both *)
  let e = V.create () in
  let f = V.create () in
  unify (Tvar e) (Tvar f);
  unify (Tvar f) (Tproduct (Tint, Tint));
  assert (canon (Tvar e) = Tproduct (Tint, Tint));
  (* an arrow against a product *)
  assert (cant_unify (Tarrow (Tint, Tint)) (Tproduct (Tint, Tint)));
  (* the failure can be deep in the types *)
  assert (cant_unify (Tarrow (Tint, Tproduct (Tint, Tint)))
                     (Tarrow (Tint, Tproduct (Tint, Tarrow (Tint, Tint)))));
  Format.printf "Question 2: additional tests passed@."
Solution of question 2
w_solutions_commented.ml, question 2
(* Question 2. Unification *)

(* unification *)

(* An exception that carries the two types that do not unify. *)
exception UnificationFailure of typ * typ

(* raise never returns, so the result type of unification_error is a type
   variable, 'a: the call is accepted wherever a value of any type is
   expected, for instance where unify expects unit. *)
let unification_error t1 t2 = raise (UnificationFailure (canon t1, canon t2))

(* The occur check: does the undefined variable v appear in the type t?
   In  Tarrow (t1, t2) | Tproduct (t1, t2)  both patterns bind the same
   names, so one branch serves for the two constructors. *)
let rec occur v t = match head t with
  | Tvar w -> V.equal v w
  | Tarrow (t1, t2) | Tproduct (t1, t2) -> occur v t1 || occur v t2
  | Tint -> false

(* unify t1 t2 makes the two types equal by defining variables, or raises
   UnificationFailure. It returns unit: its result is its effect on the
   variables. The cases, in order, on the two types after head:

     - int and int: nothing to do;
     - the same variable twice: nothing to do (the guard, after "when",
       is an extra condition on the case);
     - an undefined variable v1 and a type t2 that is not v1: the occur
       check first, since defining v1 by a type that contains v1 would
       build a cyclic type (as for  fun x -> x x); then v1 is defined
       as t2. The assert states what head guarantees: v1 is undefined;
     - a variable on the right only: the same case, with the arguments
       exchanged;
     - two arrows or two products: the components are unified pairwise;
     - anything else (int and an arrow, an arrow and a product): failure. *)
let rec unify t1 t2 = match head t1, head t2 with
  | Tint, Tint ->
      ()
  | Tvar v1, Tvar v2 when V.equal v1 v2 ->
      ()
  | Tvar v1 as t1, t2 ->
      if occur v1 t2 then unification_error t1 t2;
      assert (v1.def = None);
      v1.def <- Some t2
  | t1, Tvar v2 ->
      unify t2 t1
  | Tarrow (t11, t12), Tarrow (t21, t22)
  | Tproduct (t11, t12), Tproduct (t21, t22) ->
      unify t11 t21; unify t12 t22
  | t1, t2 ->
      unification_error t1 t2

let () =
  let a = V.create () in
  let b = V.create () in
  let ta = Tvar a in
  let tb = Tvar b in
  assert (occur a ta);
  assert (occur b tb);
  assert (not (occur a tb));
  let ty = Tarrow (ta, tb) in
  assert (occur a ty);
  assert (occur b ty);
  (* unifies 'a-> 'b and int->int *)
  unify ty (Tarrow (Tint, Tint));
  assert (canon ta = Tint);
  assert (canon ty = Tarrow (Tint, Tint));
  (* unifies 'c and int->int *)
  let c = V.create () in
  let tc = Tvar c in
  unify tc ty;
  assert (canon tc = Tarrow (Tint, Tint))

(* try ... with catches the exception: cant_unify answers true when the
   unification fails, false when it succeeds. *)
let cant_unify ty1 ty2 =
  try let _ = unify ty1 ty2 in false with UnificationFailure _ -> true

let () =
  assert (cant_unify Tint (Tarrow (Tint, Tint)));
  assert (cant_unify Tint (Tproduct (Tint, Tint)));
  let a = V.create () in
  let ta = Tvar a in
  unify ta (Tarrow (Tint, Tint));
  assert (cant_unify ta Tint)
Answers of the toplevel to these definitions
exception UnificationFailure of typ * typ
val unification_error : typ -> typ -> 'a = <fun>
val occur : tvar -> typ -> bool = <fun>
val unify : typ -> typ -> unit = <fun>
val cant_unify : typ -> typ -> bool = <fun>
Output of the additional tests, with this solution
unify   '7 -> int
with    (int * '8) -> '8
gives   (int * int) -> int
Question 2: additional tests passed

Question 3. Free variables of a type

To represent the set of free variables of a type, we use Caml's Set module.

module Vset = Set.Make(V)

Write a function

val fvars : typ -> Vset.t

that computes the set of free variables of a type. Once again, we should use the function head appropriately so as to consider only variables that are not defined.

We can test with

let () =
  assert (Vset.is_empty (fvars (Tarrow (Tint, Tint))));
  let a = V.create () in
  let ta = Tvar a in
  let ty = Tarrow (ta, ta) in
  assert (Vset.equal (fvars ty) (Vset.singleton a));
  unify ty (Tarrow (Tint, Tint));
  assert (Vset.is_empty (fvars ty))

The tab of this question in the Playground ends with additional tests, which are not from the source page:

Additional tests of question 3
let () =
  let a = V.create () in
  let b = V.create () in
  let ty = Tproduct (Tarrow (Tvar a, Tvar b), Tvar a) in
  (* a set: the variable a appears twice and counts once *)
  assert (Vset.equal (fvars ty) (Vset.add a (Vset.singleton b)));
  assert (Vset.cardinal (fvars ty) = 2);
  (* once a is defined, a is no longer free: the variables of its
     definition are *)
  unify (Tvar a) (Tarrow (Tvar b, Tint));
  Format.printf "@[<h>the type  %a  has one free variable@]@." pp_typ (canon ty);
  assert (Vset.equal (fvars ty) (Vset.singleton b));
  unify (Tvar b) Tint;
  assert (Vset.is_empty (fvars ty));
  Format.printf "Question 3: additional tests passed@."
Solution of question 3
w_solutions_commented.ml, question 3
(* Question 3. Free variables of a type *)

(* Set.Make is a functor: a function from modules to modules. Applied to
   V, it returns a module of sets whose elements have type V.t, ordered
   by V.compare: Vset.t is the type of the sets, and Vset.empty,
   Vset.singleton, Vset.union, Vset.diff and Vset.fold are among its
   operations. The sets are immutable. *)
module Vset = Set.Make(V)

(* The free variables of a type: its undefined variables. head removes
   the defined ones before each inspection. *)
let rec fvars t = match head t with
  | Tint -> Vset.empty
  | Tarrow (t1, t2) | Tproduct (t1, t2) -> Vset.union (fvars t1) (fvars t2)
  | Tvar v -> Vset.singleton v

let () =
  assert (Vset.is_empty (fvars (Tarrow (Tint, Tint))));
  let a = V.create () in
  let ta = Tvar a in
  let ty = Tarrow (ta, ta) in
  assert (Vset.equal (fvars ty) (Vset.singleton a));
  unify ty (Tarrow (Tint, Tint));
  assert (Vset.is_empty (fvars ty))
Answers of the toplevel to these definitions
module Vset :
  sig ... end
val fvars : typ -> Vset.t = <fun>
Output of the additional tests, with this solution
the type  (('9 -> int) -> '9) * ('9 -> int)  has one free variable
Question 3: additional tests passed

Question 4. Typing environment

We define the following Caml type for type schemes:

type schema = { vars : Vset.t; typ : typ }

We then introduce dictionaries using strings as keys

module Smap = Map.Make(String)

and then the following Caml type for typing environments:

type env = { bindings : schema Smap.t; fvars : Vset.t }

The first field, bindings, contains the entries of the typing environment. The second, fvars, contains the set of all free type variables in the entries of bindings. The field fvars is only there to avoid recomputing the set of free variables of the environment every time generalization is performed. Note: some of these variables may become defined between the time they are added to this set and the time it is used. We must therefore update this set before using it (for example by applying fvars (Tvar v) to each variable v and taking the union of the results).

Define the empty typing environment:

val empty : env

Write the function

val add : string -> typ -> env -> env

which adds an entry to a typing environment without generalization (it will be used for typing a function). Do not forget to update the fvars field of the environment.

Write the function

val add_gen : string -> typ -> env -> env

which adds an entry to a typing environment while generalizing its type with respect to all its free type variables that do not appear in the environment (it will be used when typing a let).

Write the function

val find : string -> env -> typ

which returns the type associated with an identifier in an environment, after replacing all variables of the corresponding scheme by fresh type variables. Careful: there may be several occurrences of the same variable in the type, and of course they must all be replaced by the same fresh variable. Hint: we can introduce a module module Vmap = Map.Make(V) and use a value of type tvar Vmap.t to represent this substitution.

The tab of this question in the Playground ends with additional tests, which are not from the source page:

Additional tests of question 4
let q4_add = add
let q4_add_gen = add_gen

let () =
  (* without generalization, find returns the type as it is, with the
     same variable: no copy *)
  let a = V.create () in
  let env = q4_add "x" (Tvar a) empty in
  assert (match canon (find "x" env) with
    | Tvar v -> V.equal v a
    | _ -> false);
  (* and the variable is now free in the environment *)
  assert (Vset.mem a env.fvars);

  (* with generalization, in the empty environment: id : 'b -> 'b becomes
     the scheme "for all 'b, 'b -> 'b", and each find returns an instance
     with a fresh variable *)
  let b = V.create () in
  let env = q4_add_gen "id" (Tarrow (Tvar b, Tvar b)) empty in
  let t1 = find "id" env in
  let t2 = find "id" env in
  Format.printf "@[<h>two instances of the scheme of id:  %a  and  %a@]@."
    pp_typ (canon t1) pp_typ (canon t2);
  (match canon t1, canon t2 with
   | Tarrow (Tvar v1, Tvar v2), Tarrow (Tvar w1, Tvar w2) ->
       (* the two occurrences of 'b get the same fresh variable *)
       assert (V.equal v1 v2);
       assert (V.equal w1 w2);
       (* fresh: not 'b itself, and not the variable of the other instance *)
       assert (not (V.equal v1 b));
       assert (not (V.equal v1 w1))
   | _ -> assert false);
  (* one instance used at int: the other instance and the scheme stay
     polymorphic *)
  unify t1 (Tarrow (Tint, Tint));
  assert (b.def = None);
  assert (match canon t2 with Tarrow (Tvar _, Tvar _) -> true | _ -> false);
  assert (match canon (find "id" env) with
    | Tarrow (Tvar _, Tvar _) -> true
    | _ -> false);

  (* a variable free in the environment is not generalized: x : 'c, then
     z : 'c with generalization; find returns 'c itself *)
  let c = V.create () in
  let env = q4_add "x" (Tvar c) empty in
  let env = q4_add_gen "z" (Tvar c) env in
  assert (match canon (find "z" env) with
    | Tvar v -> V.equal v c
    | _ -> false);

  (* the hint on free variables recorded earlier: x : 'd, then unification defines
     'd := 'e -> int. The variable 'e is now free in the environment,
     although the set recorded earlier holds 'd: 'e is not generalized *)
  let d = V.create () in
  let e = V.create () in
  let env = q4_add "x" (Tvar d) empty in
  unify (Tvar d) (Tarrow (Tvar e, Tint));
  let env = q4_add_gen "y" (Tvar e) env in
  assert (match canon (find "y" env) with
    | Tvar v -> V.equal v e
    | _ -> false);

  (* a type with both kinds of variable: in 'f -> 'g, with 'f free in the
     environment, only 'g is generalized *)
  let f = V.create () in
  let g = V.create () in
  let env = q4_add "x" (Tvar f) empty in
  let env = q4_add_gen "h" (Tarrow (Tvar f, Tvar g)) env in
  assert (match canon (find "h" env) with
    | Tarrow (Tvar v, Tvar w) -> V.equal v f && not (V.equal w g)
    | _ -> false);

  (* a later entry hides an earlier one of the same name *)
  let env = q4_add "x" Tint env in
  assert (canon (find "x" env) = Tint);
  Format.printf "Question 4: additional tests passed@."
Solution of question 4
w_solutions_commented.ml, question 4
(* Question 4. Typing environment *)

(* A type scheme: the type typ, in which the variables of the set vars
   are the quantified ones. With vars = {'a} and typ = 'a -> 'a the scheme
   is "for all 'a, 'a -> 'a". A scheme with an empty set is an ordinary
   type. *)
type schema = { vars : Vset.t; typ : typ }

(* A set of variables recorded earlier can be out of date: unification
   may have defined some of them since. norm_varset replaces each variable
   v of the set by the free variables of Tvar v: v itself when v is
   still undefined, the variables of its definition otherwise. Vset.fold
   calls the function on each element, with the set built so far. *)
let norm_varset s =
  Vset.fold (fun v s -> Vset.union (fvars (Tvar v)) s) s Vset.empty

(* Map.Make is the functor of dictionaries: Smap is a module of immutable
   dictionaries with strings as keys, and schema Smap.t is the type of
   those that associate a scheme with each key. *)
module Smap = Map.Make(String)

(* The typing environment: bindings gives the scheme of each program
   variable in scope; fvars keeps the type variables free in those
   schemes, so that generalization does not go through the whole
   environment. The field fvars and the function fvars have the same
   name without conflict: a field name is only read after a dot or inside
   braces. *)
type env = { bindings : schema Smap.t; fvars : Vset.t }

(* The environment with no entry. *)
let empty = { bindings = Smap.empty; fvars = Vset.empty }

(* add gen x t env returns the environment env extended with x of type
   t; env itself is not changed. The file has one function with a boolean
   where the page asks for two: add false is the page's add, add true is
   the page's add_gen.

   With gen = true, generalization, used at a let: the scheme quantifies
   the variables of t that are not free in the environment. A variable
   free in the environment belongs to the type of an enclosing parameter,
   and has to stay the same type at all its uses: it is not generalized.
   The set env.fvars is brought up to date by norm_varset first. The new
   entry adds no free variable to the environment.

   With gen = false, used for the parameter of a function: no variable is
   quantified, and the variables of t become free variables of the
   environment.

   let s, fvars = ...  binds the two components of a pair at once. *)
let add gen x t env =
  let vt = fvars t in
  let s, fvars =
    if gen then
      let env_fvars = norm_varset env.fvars in
      { vars = Vset.diff vt env_fvars; typ = t }, env.fvars
    else
      { vars = Vset.empty; typ = t }, Vset.union env.fvars vt
  in
  { bindings = Smap.add x s env.bindings; fvars = fvars }

(* Dictionaries with type variables as keys, for the substitution of
   find. *)
module Vmap = Map.Make(V)

(* find x env is instantiation: it returns the type of x in which every
   quantified variable of its scheme is replaced by a fresh variable.

   The dictionary s is built first, with one fresh variable for each
   quantified variable; subst then copies the type and looks each
   variable up in s. Two occurrences of the same quantified variable get
   the same fresh variable, since both are looked up in the same s. A
   variable that is not quantified is absent from s: Vmap.find raises
   Not_found, and  try ... with Not_found -> t  keeps the variable as it
   is. Each call of find builds new variables: two uses of a let-bound
   identifier get two independent copies of its type, which is what makes
   it polymorphic.

   Smap.find also raises Not_found, when x is not in the environment;
   nothing catches that one, and it ends the typing of an expression with
   an unbound variable. *)
let find x env =
  let tx = Smap.find x env.bindings in
  let s =
    Vset.fold (fun v s -> Vmap.add v (Tvar (V.create ())) s)
      tx.vars Vmap.empty
  in
  let rec subst t = match head t with
    | Tvar x as t -> (try Vmap.find x s with Not_found -> t)
    | Tint -> Tint
    | Tarrow (t1, t2) -> Tarrow (subst t1, subst t2)
    | Tproduct (t1, t2) -> Tproduct (subst t1, subst t2)
  in
  subst tx.typ
Answers of the toplevel to these definitions
type schema = { vars : Vset.t; typ : typ; }
val norm_varset : Vset.t -> Vset.t = <fun>
module Smap :
  sig ... end
type env = { bindings : schema Smap.t; fvars : Vset.t; }
val empty : env = {bindings = <abstr>; fvars = <abstr>}
val add : bool -> Smap.key -> typ -> env -> env = <fun>
module Vmap :
  sig ... end
val find : Smap.key -> env -> typ = <fun>
Output of the additional tests, with this solution
two instances of the scheme of id:  '10 -> '10  and  '11 -> '11
Question 4: additional tests passed

Question 5. Algorithm W

We are given the following type for mini-ML expressions:

type expression =
  | Var of string
  | Const of int
  | Op of string
  | Fun of string * expression
  | App of expression * expression
  | Pair of expression * expression
  | Let of string * expression * expression

Write the function

val w : env -> expression -> typ

implementing algorithm W. For operators (Op), we can restrict ourselves to Op "+" of type int * int -> int.

To test, we will use the following function

let typeof e = canon (w empty e)

Some positive tests (the expression and the expected type are indicated in comments):

(* 1 : int *)
let () = assert (typeof (Const 1) = Tint)

(* fun x -> x : 'a -> 'a *)
let () = assert (match typeof (Fun ("x", Var "x")) with
  | Tarrow (Tvar v1, Tvar v2) -> V.equal v1 v2
  | _ -> false)

(* fun x -> x+1 : int -> int *)
let () = assert (typeof (Fun ("x", App (Op "+", Pair (Var "x", Const 1))))
                 = Tarrow (Tint, Tint))

(* fun x -> x+x : int -> int *)
let () = assert (typeof (Fun ("x", App (Op "+", Pair (Var "x", Var "x"))))
                 = Tarrow (Tint, Tint))

(* let x = 1 in x+x : int *)
let () =
  assert (typeof (Let ("x", Const 1, App (Op "+", Pair (Var "x", Var "x"))))
          = Tint)

(* let id = fun x -> x in id 1 *)
let () =
  assert (typeof (Let ("id", Fun ("x", Var "x"), App (Var "id", Const 1)))
          = Tint)

(* let id = fun x -> x in id id 1 *)
let () =
  assert (typeof (Let ("id", Fun ("x", Var "x"),
                       App (App (Var "id", Var "id"), Const 1)))
          = Tint)

(* let id = fun x -> x in (id 1, id (1,2)) : int * (int * int) *)
let () =
  assert (typeof (Let ("id", Fun ("x", Var "x"),
                       Pair (App (Var "id", Const 1),
                             App (Var "id", Pair (Const 1, Const 2)))))
          = Tproduct (Tint, Tproduct (Tint, Tint)))

(* app = fun f x -> let y = f x in y : ('a -> 'b) -> 'a -> 'b *)
let () =
  let ty =
    typeof (Fun ("f", Fun ("x", Let ("y", App (Var "f", Var "x"), Var "y"))))
  in
  assert (match ty with
    | Tarrow (Tarrow (Tvar v1, Tvar v2), Tarrow (Tvar v3, Tvar v4)) ->
        V.equal v1 v3 && V.equal v2 v4
    | _ -> false)

Some negative tests:

let cant_type e =
  try let _ = typeof e in false with UnificationFailure _ -> true

(* 1 2 *)
let () = assert (cant_type (App (Const 1, Const 2)))

(* fun x -> x x *)
let () = assert (cant_type (Fun ("x", App (Var "x", Var "x"))))

(* (fun f -> +(f 1)) (fun x -> x) *)
let () = assert (cant_type
                   (App (Fun ("f", App (Op "+", App (Var "f", Const 1))),
                         Fun ("x", Var "x"))))

(* fun x -> (x 1, x (1,2)) *)
let () = assert (cant_type
                   (Fun ("x", Pair (App (Var "x", Const 1),
                                    App (Var "x", Pair (Const 1, Const 2))))))

(* fun x -> let z = x in (z 1, z (1,2)) *)
let () = assert (cant_type
                   (Fun ("x",
                         Let ("z", Var "x",
                              Pair (App (Var "z", Const 1),
                                    App (Var "z", Pair (Const 1, Const 2)))))))

(* let distr_pair = fun f -> (f 1, f (1,2)) in distr_pair (fun x -> x) *)
let () =
  assert (cant_type
            (Let ("distr_pair",
                  Fun ("f", Pair (App (Var "f", Const 1),
                                  App (Var "f", Pair (Const 1, Const 2)))),
                  App (Var "distr_pair", (Fun ("x", Var "x"))))))

The tab of this question in the Playground ends with additional tests, which are not from the source page:

Additional tests of question 5
let show source e =
  Format.printf "@[<h>%s  :  %a@]@." source pp_typ (typeof e)

let rejected source e =
  try
    show source e;
    assert false
  with UnificationFailure (t1, t2) ->
    Format.printf "@[<h>%s  is rejected:  %a  against  %a@]@."
      source pp_typ t1 pp_typ t2

let () =
  show "fun x -> fun y -> (x, y)"
    (Fun ("x", Fun ("y", Pair (Var "x", Var "y"))));
  (* twice : ('a -> 'a) -> 'a -> 'a, one variable at four places *)
  let twice =
    Fun ("f", Fun ("x", App (Var "f", App (Var "f", Var "x")))) in
  show "fun f -> fun x -> f (f x)" twice;
  assert (match typeof twice with
    | Tarrow (Tarrow (Tvar v1, Tvar v2), Tarrow (Tvar v3, Tvar v4)) ->
        V.equal v1 v2 && V.equal v2 v3 && V.equal v3 v4
    | _ -> false);
  (* the type of the function comes from its use: +(x, 1) makes x an int *)
  let succ = Fun ("x", App (Op "+", Pair (Var "x", Const 1))) in
  show "let twice = ... in twice (fun x -> x+1) 0"
    (Let ("twice", twice, App (App (Var "twice", succ), Const 0)));
  assert (typeof (Let ("twice", twice, App (App (Var "twice", succ), Const 0)))
          = Tint);
  (* a let-bound function used at two types *)
  let k = Fun ("x", Fun ("y", Var "x")) in
  let both =
    Let ("k", k,
         Pair (App (App (Var "k", Const 1), Pair (Const 1, Const 2)),
               App (App (Var "k", Pair (Const 1, Const 2)), Const 1))) in
  show "let k = fun x -> fun y -> x in (k 1 (1,2), k (1,2) 1)" both;
  assert (typeof both = Tproduct (Tint, Tproduct (Tint, Tint)));
  (* the same function bound by fun instead of let has one type only *)
  rejected "(fun k -> (k 1 (1,2), k (1,2) 1)) (fun x -> fun y -> x)"
    (App (Fun ("k",
               Pair (App (App (Var "k", Const 1), Pair (Const 1, Const 2)),
                     App (App (Var "k", Pair (Const 1, Const 2)), Const 1))),
          k));
  (* the occur check *)
  rejected "fun x -> x x" (Fun ("x", App (Var "x", Var "x")));
  (* an integer applied as a function *)
  rejected "1 2" (App (Const 1, Const 2));
  Format.printf "Question 5: additional tests passed@."
Solution of question 5
w_solutions_commented.ml, question 5
(* Question 5. Algorithm W *)

(* The abstract syntax of mini-ML. A binary operation is the application
   of an operator to a pair: x + 1 is
   App (Op "+", Pair (Var "x", Const 1)). *)
type expression =
  | Var of string
  | Const of int
  | Op of string
  | Fun of string * expression
  | App of expression * expression
  | Pair of expression * expression
  | Let of string * expression * expression

(* w env e returns the type of e in the environment env, or raises
   UnificationFailure when e is ill-typed (Not_found for a variable that
   is not bound, Failure for an unknown operator). The type returned may contain variables defined on
   the way; typeof below normalizes it. One case for each construct:

     - Var x: an instance of the scheme of x (instantiation);
     - Const: int;
     - Op "+": int * int -> int; a string pattern matches that string
       only, and any other operator falls in the next case;
     - Pair: the product of the types of the two components;
     - Fun (x, e1): the type of the parameter is not known yet, so x gets
       a fresh variable v, without generalization; typing the body e1
       defines v as far as the body constrains it. The result is
       v -> t1;
     - App (e1, e2): the type t1 of e1 has to be an arrow from the type
       t2 of e2 to some result. A fresh variable v stands for that result,
       unifying t1 with t2 -> v finds it, and v is the type of the
       application. Every type mismatch of mini-ML is a failure of this
       unification;
     - Let (x, e1, e2): the type of e1 is generalized, and e2 is typed
       with x bound to the scheme. This is the one place where
       polymorphism enters. *)
let rec w env e = match e with
  | Var x ->
      find x env
  | Const _ ->
      Tint
  | Op "+" ->
      Tarrow (Tproduct (Tint, Tint), Tint)
  | Op op ->
      failwith ("no operator " ^ op)
  | Pair (e1, e2) ->
      let t1 = w env e1 in
      let t2 = w env e2 in
      Tproduct (t1, t2)
  | Fun (x, e1) ->
      let v = Tvar (V.create ()) in
      let env = add false x v env in
      let t1 = w env e1 in
      Tarrow (v, t1)
  | App (e1, e2) ->
      let t1 = w env e1 in
      let t2 = w env e2 in
      let v = Tvar (V.create ()) in
      unify t1 (Tarrow (t2, v));
      v
  | Let (x, e1, e2) ->
      let t1 = w env e1 in
      let env = add true x t1 env in
      w env e2

(* tests *)

(* The type of a closed expression, normalized by canon. *)
let typeof e = canon (w empty e)

(* positive tests *)

(* 1 : int *)
let () = assert (typeof (Const 1) = Tint)

(* fun x -> x : 'a -> 'a *)
(* The type variable is fresh, so its id is not known in advance: the test
   checks the shape of the type, and that the two variables are the same
   one. *)
let () = assert (match typeof (Fun ("x", Var "x")) with
  | Tarrow (Tvar v1, Tvar v2) -> V.equal v1 v2
  | _ -> false)

(* fun x -> x+1 : int -> int *)
let () = assert (typeof (Fun ("x", App (Op "+", Pair (Var "x", Const 1))))
                 = Tarrow (Tint, Tint))

(* fun x -> x+x : int -> int *)
let () = assert (typeof (Fun ("x", App (Op "+", Pair (Var "x", Var "x"))))
                 = Tarrow (Tint, Tint))

(* let x = 1 in x+x : int *)
let () =
  assert (typeof (Let ("x", Const 1, App (Op "+", Pair (Var "x", Var "x"))))
          = Tint)

(* let id = fun x -> x in id 1 *)
let () =
  assert (typeof (Let ("id", Fun ("x", Var "x"), App (Var "id", Const 1)))
          = Tint)

(* let id = fun x -> x in id id 1 *)
(* id is used at two types here, ('a -> 'a) -> ('a -> 'a) and then
   int -> int: each use is a new instance of its scheme. *)
let () =
  assert (typeof (Let ("id", Fun ("x", Var "x"),
                       App (App (Var "id", Var "id"), Const 1)))
          = Tint)

(* let id = fun x -> x in (id 1, id (1,2)) : int * (int * int) *)
let () =
  let ty = typeof (Let ("id", Fun ("x", Var "x"),
                        Pair (App (Var "id", Const 1),
                              App (Var "id", Pair (Const 1, Const 2))))) in
  assert (ty
          = Tproduct (Tint, Tproduct (Tint, Tint)))

(* app = fun f x -> let y = f x in y : ('a -> 'b) -> 'a -> 'b *)
(* The type of y contains a variable that is free in the environment,
   through the type of f: it is not generalized. *)
let () =
  let ty =
    typeof (Fun ("f", Fun ("x", Let ("y", App (Var "f", Var "x"), Var "y"))))
  in
  assert (match ty with
    | Tarrow (Tarrow (Tvar v1, Tvar v2), Tarrow (Tvar v3, Tvar v4)) ->
        V.equal v1 v3 && V.equal v2 v4
    | _ -> false)

(* negative tests *)

(* true when the typing of e fails on a unification. *)
let cant_type e =
  try let _ = typeof e in false with UnificationFailure _ -> true

(* 1 2 *)
let () = assert (cant_type (App (Const 1, Const 2)))

(* fun x -> x x *)
(* The occur check: the type 'a of x would have to be 'a -> 'b. *)
let () = assert (cant_type (Fun ("x", App (Var "x", Var "x"))))

(* (fun f -> +(f 1)) (fun x -> x) *)
let () = assert (cant_type
                   (App (Fun ("f", App (Op "+", App (Var "f", Const 1))),
                         Fun ("x", Var "x"))))

(* fun x -> (x 1, x (1,2)) *)
(* A parameter is not generalized: x has one type, and it cannot accept
   both an integer and a pair. *)
let () = assert (cant_type
                   (Fun ("x", Pair (App (Var "x", Const 1),
                                    App (Var "x", Pair (Const 1, Const 2))))))

(* fun x -> let z = x in (z 1, z (1,2)) *)
(* The let does not help: the type of z is the variable of x, which is
   free in the environment, so add true leaves it out of the quantified
   variables. *)
let () = assert (cant_type
                   (Fun ("x",
                         Let ("z", Var "x",
                              Pair (App (Var "z", Const 1),
                                    App (Var "z", Pair (Const 1, Const 2)))))))

(* let distr_pair = fun f -> (f 1, f (1,2)) in distr_pair (fun x -> x) *)
let () =
  assert (cant_type
            (Let ("distr_pair",
                  Fun ("f", Pair (App (Var "f", Const 1),
                                  App (Var "f", Pair (Const 1, Const 2)))),
                  App (Var "distr_pair", (Fun ("x", Var "x"))))))
Answers of the toplevel to these definitions
type expression =
    Var of string
  | Const of int
  | Op of string
  | Fun of string * expression
  | App of expression * expression
  | Pair of expression * expression
  | Let of string * expression * expression
val w : env -> expression -> typ = <fun>
val typeof : expression -> typ = <fun>
val cant_type : expression -> bool = <fun>
Output of the additional tests, with this solution
fun x -> fun y -> (x, y)  :  '47 -> '48 -> '47 * '48
fun f -> fun x -> f (f x)  :  ('52 -> '52) -> '52 -> '52
let twice = ... in twice (fun x -> x+1) 0  :  int
let k = fun x -> fun y -> x in (k 1 (1,2), k (1,2) 1)  :  int * (int * int)
(fun k -> (k 1 (1,2), k (1,2) 1)) (fun x -> fun y -> x)  is rejected:  int  against  int * int
fun x -> x x  is rejected:  '99  against  '99 -> '100
1 2  is rejected:  int  against  int -> '101
Question 5: additional tests passed