TExcelTAD
Home › OCaml › OCaml Trees and Interpreters

OCaml Trees and Interpreters

Recursive variant types and pattern matching make OCaml one of the best languages for tree-shaped data: file systems, HTML documents, syntax trees and decision trees. This is why so many compilers and analysers are written in OCaml. In this lesson we build a binary search tree, then a tiny interpreter for a programming language.

A binary search tree

ocaml · try it yourself
type 'a tree = Leaf | Node of { left : 'a tree; value : 'a; right : 'a tree }

let rec insert x = function
  | Leaf -> Node { left = Leaf; value = x; right = Leaf }
  | Node n as t ->
      if x < n.value then Node { n with left = insert x n.left }
      else if x > n.value then Node { n with right = insert x n.right }
      else t

let rec mem x = function
  | Leaf -> false
  | Node n -> x = n.value || mem x (if x < n.value then n.left else n.right)

let rec size = function Leaf -> 0 | Node n -> size n.left + 1 + size n.right
let rec height = function Leaf -> 0 | Node n -> 1 + max (height n.left) (height n.right)

let rec fold f acc = function
  | Leaf -> acc
  | Node n -> fold f (f (fold f acc n.left) n.value) n.right

let () =
  let t = List.fold_left (fun t x -> insert x t) Leaf [ 50; 30; 70; 20; 40; 60; 80; 35 ] in
  Printf.printf "size %d, height %d\n" (size t) (height t);
  Printf.printf "mem 40: %b, mem 45: %b\n" (mem 40 t) (mem 45 t);
  let in_order = List.rev (fold (fun acc x -> x :: acc) [] t) in
  print_endline (String.concat " " (List.map string_of_int in_order))
size 8, height 4
mem 40: true, mem 45: false
20 30 35 40 50 60 70 80

Each function follows the shape of the type: one case for Leaf, one for Node. Insertion builds a new tree that shares all unchanged subtrees with the old one, so it costs only O(height) allocations.

Drawing a tree

ocaml · try it yourself
type 'a tree = Leaf | Node of 'a tree * 'a * 'a tree

let rec insert x = function
  | Leaf -> Node (Leaf, x, Leaf)
  | Node (l, v, r) as t -> if x < v then Node (insert x l, v, r) else if x > v then Node (l, v, insert x r) else t

let rec draw indent = function
  | Leaf -> ()
  | Node (l, v, r) ->
      draw (indent ^ "    ") r;
      Printf.printf "%s%s\n" indent v;
      draw (indent ^ "    ") l

let () = List.fold_left (fun t x -> insert x t) Leaf [ "m"; "f"; "t"; "b"; "h"; "w" ] |> draw ""
        w
    t
m
        h
    f
        b

Read it with your head tilted to the left: the root m is on the left, larger values are above.

An interpreter for arithmetic with variables

An abstract syntax tree (AST) represents a program as a tree. Let's model a tiny language with numbers, variables, arithmetic, let and if:

ocaml · try it yourself
type expr =
  | Int of int
  | Var of string
  | Add of expr * expr
  | Sub of expr * expr
  | Mul of expr * expr
  | Div of expr * expr
  | Let of string * expr * expr          (* let x = e1 in e2 *)
  | If_zero of expr * expr * expr         (* if e = 0 then a else b *)

exception Eval_error of string

let rec eval env = function
  | Int n -> n
  | Var x -> (
      match List.assoc_opt x env with
      | Some v -> v
      | None -> raise (Eval_error ("unbound variable " ^ x)))
  | Add (a, b) -> eval env a + eval env b
  | Sub (a, b) -> eval env a - eval env b
  | Mul (a, b) -> eval env a * eval env b
  | Div (a, b) ->
      let d = eval env b in
      if d = 0 then raise (Eval_error "division by zero") else eval env a / d
  | Let (x, e1, e2) -> eval ((x, eval env e1) :: env) e2
  | If_zero (c, a, b) -> if eval env c = 0 then eval env a else eval env b

let rec to_string = function
  | Int n -> string_of_int n
  | Var x -> x
  | Add (a, b) -> "(" ^ to_string a ^ " + " ^ to_string b ^ ")"
  | Sub (a, b) -> "(" ^ to_string a ^ " - " ^ to_string b ^ ")"
  | Mul (a, b) -> "(" ^ to_string a ^ " * " ^ to_string b ^ ")"
  | Div (a, b) -> "(" ^ to_string a ^ " / " ^ to_string b ^ ")"
  | Let (x, e1, e2) -> "let " ^ x ^ " = " ^ to_string e1 ^ " in " ^ to_string e2
  | If_zero (c, a, b) -> "if " ^ to_string c ^ " = 0 then " ^ to_string a ^ " else " ^ to_string b

let run e =
  match eval [] e with
  | v -> Printf.printf "%s\n  => %d\n" (to_string e) v
  | exception Eval_error msg -> Printf.printf "%s\n  => error: %s\n" (to_string e) msg

let () =
  run (Let ("x", Int 6, Mul (Var "x", Add (Var "x", Int 1))));
  run (Let ("a", Int 10, Let ("b", Sub (Var "a", Int 10), If_zero (Var "b", Int 1, Div (Var "a", Var "b")))));
  run (Div (Int 1, Sub (Int 2, Int 2)));
  run (Add (Var "y", Int 1))
let x = 6 in (x * (x + 1))
  => 42
let a = 10 in let b = (a - 10) in if b = 0 then 1 else (a / b)
  => 1
(1 / (2 - 2))
  => error: division by zero
(y + 1)
  => error: unbound variable y

The environment env is an association list from variable names to values. Let evaluates the bound expression and adds the result in front, so inner bindings shadow outer ones.

Transforming trees: constant folding

Compilers also rewrite trees. A simplifier that folds constants and removes x * 1 and x + 0 is one function with a few patterns:

ocaml · try it yourself
type expr = Int of int | Var of string | Add of expr * expr | Mul of expr * expr

let rec simplify e =
  match e with
  | Int _ | Var _ -> e
  | Add (a, b) -> (
      match (simplify a, simplify b) with
      | Int x, Int y -> Int (x + y)
      | Int 0, e' | e', Int 0 -> e'
      | a', b' -> Add (a', b'))
  | Mul (a, b) -> (
      match (simplify a, simplify b) with
      | Int x, Int y -> Int (x * y)
      | Int 0, _ | _, Int 0 -> Int 0
      | Int 1, e' | e', Int 1 -> e'
      | a', b' -> Mul (a', b'))

let rec show = function
  | Int n -> string_of_int n
  | Var x -> x
  | Add (a, b) -> "(" ^ show a ^ " + " ^ show b ^ ")"
  | Mul (a, b) -> show a ^ " * " ^ show b

let () =
  let e = Add (Mul (Int 1, Var "x"), Mul (Add (Int 2, Int 3), Add (Var "y", Int 0))) in
  Printf.printf "%s\n=> %s\n" (show e) (show (simplify e))
(1 * x + (2 + 3) * (y + 0))
=> (x + 5 * y)

Three rules fired: 1 * x became x, 2 + 3 was folded to 5, and y + 0 became y. Because simplify first simplifies the children and then looks at the result, rules can enable each other.

Test yourself

Why are recursive variants a good fit for syntax trees?

  1. They are mutable
  2. Each kind of node is a constructor, and pattern matching handles each kind
  3. They are stored in arrays
  4. They avoid recursion

In the interpreter, how does Let (x, e1, e2) make x visible in e2?

  1. It mutates a global table
  2. It evaluates e2 in an environment extended with (x, value of e1)
  3. It replaces x in the source text
  4. It raises an exception

What does inserting into an immutable binary search tree return?

  1. unit
  2. The same tree, modified
  3. A new tree that shares the unchanged subtrees
  4. A list