annotate lab0/eval.ml @ 0:bfdcc3820b32

Basis
author Mike Spivey <mike@cs.ox.ac.uk>
date Thu, 05 Oct 2017 08:04:15 +0100
parents
children
rev   line source
0
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
1 (* lab1/eval.ml *)
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
2 (* Copyright (c) 2017 J. M. Spivey *)
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
3
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
4 open Tree
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
5
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
6 (* |do_binop| -- compute result of binary operator *)
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
7 let do_binop w v1 v2 =
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
8 match w with
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
9 Plus -> v1 +. v2
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
10 | Minus -> v1 -. v2
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
11 | Times -> v1 *. v2
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
12 | Divide ->
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
13 if v2 = 0.0 then failwith "dividing by zero";
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
14 v1 /. v2
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
15
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
16 (* |eval_expr| -- evaluate an expression *)
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
17 let rec eval_expr =
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
18 function
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
19 Number r -> r
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
20 | Variable x -> failwith "Sorry, I don't do variables"
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
21 | Binop (w, e1, e2) ->
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
22 do_binop w (eval_expr e1) (eval_expr e2)
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
23
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
24 (* |process| -- process an equation, return value of RHS *)
Mike Spivey <mike@cs.ox.ac.uk>
parents:
diff changeset
25 let process (x, e) = eval_expr e