TExcelTAD
Home › OCaml › OCaml Mini Project

OCaml Mini Project

In this project you will build a calculator language, step by step: a tokenizer, a parser and an evaluator, with variables, functions and helpful error messages. It is a small version of what compilers do, and it uses much of the course: variants, records, pattern matching, recursion, Map, result and let*.

By the end, the calculator runs sessions like this:

text
> let r = 2.5
r = 2.5
> let area = 3.14159 * r ^ 2
area = 19.6349
> max(area, 20) / (1 - 1)
error: division by zero

Every step is a complete program you can run and change. Because the playground cannot read keyboard input, the "user" is simulated by a list of input lines. In a terminal you would read them with In_channel.input_line stdin in a loop.

Step 1: The syntax tree

First, decide what an expression is. A variant type describes every kind of expression, and eval and to_string follow its shape:

ocaml · try it yourself
type binop = Add | Sub | Mul | Div | Pow

type expr =
  | Num of float
  | Neg of expr
  | Binop of binop * expr * expr

let rec eval = function
  | Num f -> f
  | Neg e -> -.eval e
  | Binop (op, a, b) -> (
      let x = eval a and y = eval b in
      match op with Add -> x +. y | Sub -> x -. y | Mul -> x *. y | Div -> x /. y | Pow -> x ** y)

let symbol = function Add -> "+" | Sub -> "-" | Mul -> "*" | Div -> "/" | Pow -> "^"

let rec to_string = function
  | Num f -> Printf.sprintf "%g" f
  | Neg e -> "-" ^ to_string e
  | Binop (op, a, b) -> "(" ^ to_string a ^ " " ^ symbol op ^ " " ^ to_string b ^ ")"

let () =
  (* (1 + 2) * -3 ^ 2, written by hand as a tree *)
  let e = Binop (Mul, Binop (Add, Num 1., Num 2.), Neg (Binop (Pow, Num 3., Num 2.))) in
  Printf.printf "%s = %g\n" (to_string e) (eval e)
((1 + 2) * -(3 ^ 2)) = -27

Writing trees by hand is tedious. The next two steps turn text into trees automatically.

Step 2: The tokenizer

A tokenizer (lexer) cuts the input string into tokens: numbers, names and symbols. Spaces are skipped. Unknown characters produce an Error with the position:

ocaml · try it yourself
type token =
  | NUM of float | IDENT of string
  | PLUS | MINUS | STAR | SLASH | CARET | LPAREN | RPAREN | COMMA | EQUALS

let show_token = function
  | NUM f -> Printf.sprintf "%g" f | IDENT s -> s
  | PLUS -> "+" | MINUS -> "-" | STAR -> "*" | SLASH -> "/" | CARET -> "^"
  | LPAREN -> "(" | RPAREN -> ")" | COMMA -> "," | EQUALS -> "="

let tokenize s =
  let n = String.length s in
  let rec scan p i = if i < n && p s.[i] then scan p (i + 1) else i in
  let is_digit c = (c >= '0' && c <= '9') || c = '.' in
  let is_ident c = match c with 'a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9' -> true | _ -> false in
  let rec go i acc =
    if i >= n then Ok (List.rev acc)
    else
      let single tok = go (i + 1) (tok :: acc) in
      match s.[i] with
      | ' ' | '\t' -> go (i + 1) acc
      | '+' -> single PLUS | '-' -> single MINUS | '*' -> single STAR | '/' -> single SLASH
      | '^' -> single CARET | '(' -> single LPAREN | ')' -> single RPAREN
      | ',' -> single COMMA | '=' -> single EQUALS
      | '0' .. '9' | '.' -> (
          let j = scan is_digit i in
          let text = String.sub s i (j - i) in
          match float_of_string_opt text with
          | Some f -> go j (NUM f :: acc)
          | None -> Error (Printf.sprintf "bad number %S at position %d" text i))
      | 'a' .. 'z' | 'A' .. 'Z' | '_' ->
          let j = scan is_ident i in
          go j (IDENT (String.sub s i (j - i)) :: acc)
      | c -> Error (Printf.sprintf "unexpected character '%c' at position %d" c i)
  in
  go 0 []

let () =
  List.iter
    (fun input ->
      match tokenize input with
      | Ok toks -> Printf.printf "%-18s -> %s\n" input (String.concat " | " (List.map show_token toks))
      | Error msg -> Printf.printf "%-18s -> error: %s\n" input msg)
    [ "1 + 2*3"; "let rate = 0.25"; "max(x, 10)^2"; "4 % 2"; "1.2.3" ]
1 + 2*3            -> 1 | + | 2 | * | 3
let rate = 0.25    -> let | rate | = | 0.25
max(x, 10)^2       -> max | ( | x | , | 10 | ) | ^ | 2
4 % 2              -> error: unexpected character '%' at position 2
1.2.3              -> error: bad number "1.2.3" at position 0

Step 3: The parser

The parser turns a token list into a tree, respecting precedence: ^ binds tighter than * and /, which bind tighter than + and -. A classic recursive descent parser has one function per precedence level. Each function returns the parsed expression together with the remaining tokens:

text
expr  := term   (('+' | '-') term)*
term  := unary  (('*' | '/') unary)*
unary := '-' unary | power
power := atom   ('^' unary)?             right-associative: 2^3^2 = 2^(3^2)
atom  := number | name | name '(' args ')' | '(' expr ')'
ocaml · try it yourself
type token =
  | NUM of float | IDENT of string
  | PLUS | MINUS | STAR | SLASH | CARET | LPAREN | RPAREN | COMMA | EQUALS

let show_token = function
  | NUM f -> Printf.sprintf "%g" f | IDENT s -> s
  | PLUS -> "+" | MINUS -> "-" | STAR -> "*" | SLASH -> "/" | CARET -> "^"
  | LPAREN -> "(" | RPAREN -> ")" | COMMA -> "," | EQUALS -> "="

type binop = Add | Sub | Mul | Div | Pow

type expr =
  | Num of float
  | Var of string
  | Neg of expr
  | Binop of binop * expr * expr
  | Call of string * expr list

exception Syntax_error of string

let rec parse_expr toks =
  let rec loop lhs = function
    | PLUS :: rest -> let rhs, rest = parse_term rest in loop (Binop (Add, lhs, rhs)) rest
    | MINUS :: rest -> let rhs, rest = parse_term rest in loop (Binop (Sub, lhs, rhs)) rest
    | rest -> (lhs, rest)
  in
  let lhs, rest = parse_term toks in
  loop lhs rest

and parse_term toks =
  let rec loop lhs = function
    | STAR :: rest -> let rhs, rest = parse_unary rest in loop (Binop (Mul, lhs, rhs)) rest
    | SLASH :: rest -> let rhs, rest = parse_unary rest in loop (Binop (Div, lhs, rhs)) rest
    | rest -> (lhs, rest)
  in
  let lhs, rest = parse_unary toks in
  loop lhs rest

and parse_unary = function
  | MINUS :: rest -> let e, rest = parse_unary rest in (Neg e, rest)
  | toks -> parse_power toks

and parse_power toks =
  match parse_atom toks with
  | base, CARET :: rest -> let exp, rest = parse_unary rest in (Binop (Pow, base, exp), rest)
  | result -> result

and parse_atom = function
  | NUM f :: rest -> (Num f, rest)
  | IDENT name :: LPAREN :: rest -> let args, rest = parse_args rest in (Call (name, args), rest)
  | IDENT name :: rest -> (Var name, rest)
  | LPAREN :: rest -> (
      match parse_expr rest with
      | e, RPAREN :: rest -> (e, rest)
      | _ -> raise (Syntax_error "expected ')'"))
  | tok :: _ -> raise (Syntax_error ("unexpected '" ^ show_token tok ^ "'"))
  | [] -> raise (Syntax_error "unexpected end of input")

and parse_args toks =
  let first, rest = parse_expr toks in
  match rest with
  | COMMA :: rest -> let others, rest = parse_args rest in (first :: others, rest)
  | RPAREN :: rest -> ([ first ], rest)
  | _ -> raise (Syntax_error "expected ',' or ')' in arguments")

let parse toks =
  match parse_expr toks with
  | e, [] -> e
  | _, tok :: _ -> raise (Syntax_error ("unexpected '" ^ show_token tok ^ "' after expression"))

let symbol = function Add -> "+" | Sub -> "-" | Mul -> "*" | Div -> "/" | Pow -> "^"

let rec to_string = function
  | Num f -> Printf.sprintf "%g" f
  | Var x -> x
  | Neg e -> "-" ^ to_string e
  | Binop (op, a, b) -> "(" ^ to_string a ^ " " ^ symbol op ^ " " ^ to_string b ^ ")"
  | Call (f, args) -> f ^ "(" ^ String.concat ", " (List.map to_string args) ^ ")"

let () =
  (* token lists written by hand here; step 4 connects the tokenizer *)
  let examples =
    [ [ NUM 1.; PLUS; NUM 2.; STAR; NUM 3. ];
      [ NUM 2.; CARET; NUM 3.; CARET; NUM 2. ];
      [ MINUS; NUM 2.; CARET; NUM 2. ];
      [ NUM 10.; MINUS; NUM 4.; MINUS; NUM 3. ];
      [ IDENT "max"; LPAREN; IDENT "x"; COMMA; NUM 1.; PLUS; NUM 1.; RPAREN ];
      [ LPAREN; NUM 1.; PLUS; NUM 2. ];
      [ NUM 1.; NUM 2. ] ]
  in
  List.iter
    (fun toks ->
      let src = String.concat " " (List.map show_token toks) in
      match parse toks with
      | e -> Printf.printf "%-22s => %s\n" src (to_string e)
      | exception Syntax_error msg -> Printf.printf "%-22s => syntax error: %s\n" src msg)
    examples
1 + 2 * 3              => (1 + (2 * 3))
2 ^ 3 ^ 2              => (2 ^ (3 ^ 2))
- 2 ^ 2                => -(2 ^ 2)
10 - 4 - 3             => ((10 - 4) - 3)
max ( x , 1 + 1 )      => max(x, (1 + 1))
( 1 + 2                => syntax error: expected ')'
1 2                    => syntax error: unexpected '2' after expression

The fully parenthesised output proves the precedence rules: * before +, ^ grouping to the right, and - grouping to the left (10 - 4 - 3 is (10 - 4) - 3 = 3, not 10 - (4 - 3) = 9).

Step 4: Evaluation with variables, functions and errors

Now the evaluator. Variables live in an immutable Map (the environment), built-in functions are looked up by name, and every failure becomes a value of a precise error variant. Evaluation returns a result, and let* chains the steps. The parser still uses an exception internally, but calculate converts it, so callers only ever see result:

ocaml · try it yourself
type token =
  | NUM of float | IDENT of string
  | PLUS | MINUS | STAR | SLASH | CARET | LPAREN | RPAREN | COMMA | EQUALS

let show_token = function
  | NUM f -> Printf.sprintf "%g" f | IDENT s -> s
  | PLUS -> "+" | MINUS -> "-" | STAR -> "*" | SLASH -> "/" | CARET -> "^"
  | LPAREN -> "(" | RPAREN -> ")" | COMMA -> "," | EQUALS -> "="

let tokenize s =
  let n = String.length s in
  let rec scan p i = if i < n && p s.[i] then scan p (i + 1) else i in
  let is_digit c = (c >= '0' && c <= '9') || c = '.' in
  let is_ident c = match c with 'a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9' -> true | _ -> false in
  let rec go i acc =
    if i >= n then Ok (List.rev acc)
    else
      let single tok = go (i + 1) (tok :: acc) in
      match s.[i] with
      | ' ' | '\t' -> go (i + 1) acc
      | '+' -> single PLUS | '-' -> single MINUS | '*' -> single STAR | '/' -> single SLASH
      | '^' -> single CARET | '(' -> single LPAREN | ')' -> single RPAREN
      | ',' -> single COMMA | '=' -> single EQUALS
      | '0' .. '9' | '.' -> (
          let j = scan is_digit i in
          let text = String.sub s i (j - i) in
          match float_of_string_opt text with
          | Some f -> go j (NUM f :: acc)
          | None -> Error (Printf.sprintf "bad number %S at position %d" text i))
      | 'a' .. 'z' | 'A' .. 'Z' | '_' ->
          let j = scan is_ident i in
          go j (IDENT (String.sub s i (j - i)) :: acc)
      | c -> Error (Printf.sprintf "unexpected character '%c' at position %d" c i)
  in
  go 0 []

type binop = Add | Sub | Mul | Div | Pow
type expr = Num of float | Var of string | Neg of expr | Binop of binop * expr * expr | Call of string * expr list

exception Syntax_error of string

let rec parse_expr toks =
  let rec loop lhs = function
    | PLUS :: rest -> let rhs, rest = parse_term rest in loop (Binop (Add, lhs, rhs)) rest
    | MINUS :: rest -> let rhs, rest = parse_term rest in loop (Binop (Sub, lhs, rhs)) rest
    | rest -> (lhs, rest)
  in
  let lhs, rest = parse_term toks in
  loop lhs rest

and parse_term toks =
  let rec loop lhs = function
    | STAR :: rest -> let rhs, rest = parse_unary rest in loop (Binop (Mul, lhs, rhs)) rest
    | SLASH :: rest -> let rhs, rest = parse_unary rest in loop (Binop (Div, lhs, rhs)) rest
    | rest -> (lhs, rest)
  in
  let lhs, rest = parse_unary toks in
  loop lhs rest

and parse_unary = function
  | MINUS :: rest -> let e, rest = parse_unary rest in (Neg e, rest)
  | toks -> parse_power toks

and parse_power toks =
  match parse_atom toks with
  | base, CARET :: rest -> let exp, rest = parse_unary rest in (Binop (Pow, base, exp), rest)
  | result -> result

and parse_atom = function
  | NUM f :: rest -> (Num f, rest)
  | IDENT name :: LPAREN :: rest -> let args, rest = parse_args rest in (Call (name, args), rest)
  | IDENT name :: rest -> (Var name, rest)
  | LPAREN :: rest -> (
      match parse_expr rest with e, RPAREN :: rest -> (e, rest) | _ -> raise (Syntax_error "expected ')'"))
  | tok :: _ -> raise (Syntax_error ("unexpected '" ^ show_token tok ^ "'"))
  | [] -> raise (Syntax_error "unexpected end of input")

and parse_args toks =
  let first, rest = parse_expr toks in
  match rest with
  | COMMA :: rest -> let others, rest = parse_args rest in (first :: others, rest)
  | RPAREN :: rest -> ([ first ], rest)
  | _ -> raise (Syntax_error "expected ',' or ')' in arguments")

let parse toks =
  match parse_expr toks with
  | e, [] -> e
  | _, tok :: _ -> raise (Syntax_error ("unexpected '" ^ show_token tok ^ "' after expression"))

(* ---- new in this step ---- *)
module Env = Map.Make (String)

type error =
  | Syntax of string
  | Unbound_variable of string
  | Unknown_function of string
  | Bad_arguments of string
  | Division_by_zero

let error_to_string = function
  | Syntax msg -> "syntax error: " ^ msg
  | Unbound_variable x -> "unknown variable '" ^ x ^ "'"
  | Unknown_function f -> "unknown function '" ^ f ^ "'"
  | Bad_arguments msg -> msg
  | Division_by_zero -> "division by zero"

let ( let* ) = Result.bind

let call name args =
  match (name, args) with
  | "sqrt", [ x ] -> if x < 0. then Error (Bad_arguments "sqrt of a negative number") else Ok (sqrt x)
  | "abs", [ x ] -> Ok (Float.abs x)
  | ("max" | "min"), x :: rest -> Ok (List.fold_left (if name = "max" then Float.max else Float.min) x rest)
  | ("sqrt" | "abs"), _ -> Error (Bad_arguments (name ^ " takes exactly 1 argument"))
  | _ -> Error (Unknown_function name)

let rec eval env = function
  | Num f -> Ok f
  | Var x -> Option.to_result ~none:(Unbound_variable x) (Env.find_opt x env)
  | Neg e -> let* v = eval env e in Ok (-.v)
  | Binop (op, a, b) -> (
      let* x = eval env a in
      let* y = eval env b in
      match op with
      | Add -> Ok (x +. y)
      | Sub -> Ok (x -. y)
      | Mul -> Ok (x *. y)
      | Div -> if y = 0. then Error Division_by_zero else Ok (x /. y)
      | Pow -> Ok (x ** y))
  | Call (f, args) ->
      let* values = eval_all env args in
      call f values

and eval_all env = function
  | [] -> Ok []
  | e :: rest ->
      let* v = eval env e in
      let* vs = eval_all env rest in
      Ok (v :: vs)

let calculate env input =
  let* toks = Result.map_error (fun m -> Syntax m) (tokenize input) in
  let* tree = try Ok (parse toks) with Syntax_error m -> Error (Syntax m) in
  eval env tree

let () =
  let env = Env.(empty |> add "pi" Float.pi |> add "x" 4.) in
  List.iter
    (fun input ->
      match calculate env input with
      | Ok v -> Printf.printf "%-20s = %g\n" input v
      | Error e -> Printf.printf "%-20s ! %s\n" input (error_to_string e))
    [ "2 * pi * x"; "sqrt(x) + 2^-1"; "max(1, x, 3) - min(9, 2)"; "10 / (x - 4)"; "y + 1"; "sqrt(-x)";
      "abs(1, 2)"; "log(10)"; "3 +"; "2 $ 3" ]
2 * pi * x           = 25.1327
sqrt(x) + 2^-1       = 2.5
max(1, x, 3) - min(9, 2) = 2
10 / (x - 4)         ! division by zero
y + 1                ! unknown variable 'y'
sqrt(-x)             ! sqrt of a negative number
abs(1, 2)            ! abs takes exactly 1 argument
log(10)              ! unknown function 'log'
3 +                  ! syntax error: unexpected end of input
2 $ 3                ! syntax error: unexpected character '
  

 at position 2

Notice how little error-handling code eval needs: each let* passes an Error straight through, so the first problem stops the evaluation and is reported.

Step 5: An interactive session

Finally, a small REPL (read-eval-print loop). A line is either let name = expression, which stores a variable, or a plain expression. The environment is threaded through the session with List.fold_left: each line receives the environment produced by the previous one. The special command vars lists the variables (in sorted order, thanks to Map):

ocaml · try it yourself
type token =
  | NUM of float | IDENT of string
  | PLUS | MINUS | STAR | SLASH | CARET | LPAREN | RPAREN | COMMA | EQUALS

let show_token = function
  | NUM f -> Printf.sprintf "%g" f | IDENT s -> s
  | PLUS -> "+" | MINUS -> "-" | STAR -> "*" | SLASH -> "/" | CARET -> "^"
  | LPAREN -> "(" | RPAREN -> ")" | COMMA -> "," | EQUALS -> "="

let tokenize s =
  let n = String.length s in
  let rec scan p i = if i < n && p s.[i] then scan p (i + 1) else i in
  let is_digit c = (c >= '0' && c <= '9') || c = '.' in
  let is_ident c = match c with 'a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9' -> true | _ -> false in
  let rec go i acc =
    if i >= n then Ok (List.rev acc)
    else
      let single tok = go (i + 1) (tok :: acc) in
      match s.[i] with
      | ' ' | '\t' -> go (i + 1) acc
      | '+' -> single PLUS | '-' -> single MINUS | '*' -> single STAR | '/' -> single SLASH
      | '^' -> single CARET | '(' -> single LPAREN | ')' -> single RPAREN
      | ',' -> single COMMA | '=' -> single EQUALS
      | '0' .. '9' | '.' -> (
          let j = scan is_digit i in
          let text = String.sub s i (j - i) in
          match float_of_string_opt text with
          | Some f -> go j (NUM f :: acc)
          | None -> Error (Printf.sprintf "bad number %S at position %d" text i))
      | 'a' .. 'z' | 'A' .. 'Z' | '_' ->
          let j = scan is_ident i in
          go j (IDENT (String.sub s i (j - i)) :: acc)
      | c -> Error (Printf.sprintf "unexpected character '%c' at position %d" c i)
  in
  go 0 []

type binop = Add | Sub | Mul | Div | Pow
type expr = Num of float | Var of string | Neg of expr | Binop of binop * expr * expr | Call of string * expr list

exception Syntax_error of string

let rec parse_expr toks =
  let rec loop lhs = function
    | PLUS :: rest -> let rhs, rest = parse_term rest in loop (Binop (Add, lhs, rhs)) rest
    | MINUS :: rest -> let rhs, rest = parse_term rest in loop (Binop (Sub, lhs, rhs)) rest
    | rest -> (lhs, rest)
  in
  let lhs, rest = parse_term toks in
  loop lhs rest

and parse_term toks =
  let rec loop lhs = function
    | STAR :: rest -> let rhs, rest = parse_unary rest in loop (Binop (Mul, lhs, rhs)) rest
    | SLASH :: rest -> let rhs, rest = parse_unary rest in loop (Binop (Div, lhs, rhs)) rest
    | rest -> (lhs, rest)
  in
  let lhs, rest = parse_unary toks in
  loop lhs rest

and parse_unary = function
  | MINUS :: rest -> let e, rest = parse_unary rest in (Neg e, rest)
  | toks -> parse_power toks

and parse_power toks =
  match parse_atom toks with
  | base, CARET :: rest -> let exp, rest = parse_unary rest in (Binop (Pow, base, exp), rest)
  | result -> result

and parse_atom = function
  | NUM f :: rest -> (Num f, rest)
  | IDENT name :: LPAREN :: rest -> let args, rest = parse_args rest in (Call (name, args), rest)
  | IDENT name :: rest -> (Var name, rest)
  | LPAREN :: rest -> (
      match parse_expr rest with e, RPAREN :: rest -> (e, rest) | _ -> raise (Syntax_error "expected ')'"))
  | tok :: _ -> raise (Syntax_error ("unexpected '" ^ show_token tok ^ "'"))
  | [] -> raise (Syntax_error "unexpected end of input")

and parse_args toks =
  let first, rest = parse_expr toks in
  match rest with
  | COMMA :: rest -> let others, rest = parse_args rest in (first :: others, rest)
  | RPAREN :: rest -> ([ first ], rest)
  | _ -> raise (Syntax_error "expected ',' or ')' in arguments")

let parse toks =
  match parse_expr toks with
  | e, [] -> e
  | _, tok :: _ -> raise (Syntax_error ("unexpected '" ^ show_token tok ^ "' after expression"))

module Env = Map.Make (String)

type error =
  | Syntax of string
  | Unbound_variable of string
  | Unknown_function of string
  | Bad_arguments of string
  | Division_by_zero

let error_to_string = function
  | Syntax msg -> "syntax error: " ^ msg
  | Unbound_variable x -> "unknown variable '" ^ x ^ "'"
  | Unknown_function f -> "unknown function '" ^ f ^ "'"
  | Bad_arguments msg -> msg
  | Division_by_zero -> "division by zero"

let ( let* ) = Result.bind

let call name args =
  match (name, args) with
  | "sqrt", [ x ] -> if x < 0. then Error (Bad_arguments "sqrt of a negative number") else Ok (sqrt x)
  | "abs", [ x ] -> Ok (Float.abs x)
  | ("max" | "min"), x :: rest -> Ok (List.fold_left (if name = "max" then Float.max else Float.min) x rest)
  | ("sqrt" | "abs"), _ -> Error (Bad_arguments (name ^ " takes exactly 1 argument"))
  | _ -> Error (Unknown_function name)

let rec eval env = function
  | Num f -> Ok f
  | Var x -> Option.to_result ~none:(Unbound_variable x) (Env.find_opt x env)
  | Neg e -> let* v = eval env e in Ok (-.v)
  | Binop (op, a, b) -> (
      let* x = eval env a in
      let* y = eval env b in
      match op with
      | Add -> Ok (x +. y)
      | Sub -> Ok (x -. y)
      | Mul -> Ok (x *. y)
      | Div -> if y = 0. then Error Division_by_zero else Ok (x /. y)
      | Pow -> Ok (x ** y))
  | Call (f, args) ->
      let* values = eval_all env args in
      call f values

and eval_all env = function
  | [] -> Ok []
  | e :: rest ->
      let* v = eval env e in
      let* vs = eval_all env rest in
      Ok (v :: vs)

(* ---- new in this step ---- *)
let parse_tokens toks = try Ok (parse toks) with Syntax_error m -> Error (Syntax m)

(* run one line: returns the new environment and the text to print *)
let run_line env line =
  match tokenize line with
  | Error m -> (env, "error: " ^ error_to_string (Syntax m))
  | Ok [ IDENT "vars" ] ->
      let shown = Env.bindings env |> List.map (fun (k, v) -> Printf.sprintf "%s=%g" k v) in
      (env, String.concat ", " shown)
  | Ok (IDENT "let" :: IDENT name :: EQUALS :: rest) -> (
      match Result.bind (parse_tokens rest) (eval env) with
      | Ok v -> (Env.add name v env, Printf.sprintf "%s = %g" name v)
      | Error e -> (env, "error: " ^ error_to_string e))
  | Ok toks -> (
      match Result.bind (parse_tokens toks) (eval env) with
      | Ok v -> (Env.add "ans" v env, Printf.sprintf "%g" v)
      | Error e -> (env, "error: " ^ error_to_string e))

let session =
  [ "let r = 2.5";
    "let area = 3.14159 * r ^ 2";
    "max(area, 20) / (1 - 1)";
    "area / 2";
    "ans + 0.5";
    "let r = r * 2";
    "let big = 3.14159 * r ^ 2";
    "big / area";
    "let oops = rr + 1";
    "vars" ]

let () =
  let final_env =
    List.fold_left
      (fun env line ->
        Printf.printf "> %s\n" line;
        let env, output = run_line env line in
        print_endline output;
        env)
      (Env.singleton "pi" Float.pi) session
  in
  Printf.printf "(%d variables at the end)\n" (Env.cardinal final_env)
> let r = 2.5
r = 2.5
> let area = 3.14159 * r ^ 2
area = 19.6349
> max(area, 20) / (1 - 1)
error: division by zero
> area / 2
9.81747
> ans + 0.5
10.3175
> let r = r * 2
r = 5
> let big = 3.14159 * r ^ 2
big = 78.5397
> big / area
4
> let oops = rr + 1
error: unknown variable 'rr'
> vars
ans=4, area=19.6349, big=78.5397, pi=3.14159, r=5
(5 variables at the end)

A few design points worth noticing:

  • The environment is immutable. A failed line returns the old environment unchanged, so an error can never leave the calculator half-updated.
  • ans holds the last result, like a pocket calculator. It is just another variable.
  • Pattern matching on the token list (IDENT "let" :: IDENT name :: EQUALS :: rest) recognises statements without a separate grammar.

Ideas to extend the project

  1. Add the % (remainder) operator: one token, one binop constructor, one line in parse_term and in eval. The compiler's exhaustiveness warnings will point at every match to update.
  2. Add user-defined functions: def square(x) = x * x. Store an expr and its parameter names in a second map.
  3. Report error positions: keep the character offset in each token.
  4. Replace the parse exception with a result-returning parser using let*.
  5. Add a simplify pass (constant folding) like in the trees lesson, and print the simplified expression.
  6. Split the code into modules Lexer, Parser and Eval with .mli signatures in a dune project, and write tests for each.

Test yourself

Why does the parser have separate functions parse_expr, parse_term and parse_power?

  1. For speed
  2. Each one handles one precedence level, so * binds tighter than +
  3. OCaml requires one function per token
  4. To avoid recursion

What happens to the environment when a let line fails to evaluate?

  1. The variable is set to 0
  2. The old environment is returned unchanged
  3. The program stops
  4. All variables are deleted

How does let* simplify eval?

  1. It makes evaluation lazy
  2. It stops at the first Error and passes it on without explicit matches
  3. It catches exceptions
  4. It caches results