1 (* calc3.ml: calc2.ml enhanced with Recursive Function Values *)
5 | Multiplication of (term * term)
6 | Addition of (term * term)
8 | Let of (char * term * term)
10 | If of (term * term * term)
11 | Makepair of (term * term)
13 | Lambda of (char * term)
14 | Apply of (term * term)
15 | Letrec of (char * term * term)
18 type bound_value = Nonrecursive of expressed_value | Recursive_Closure of char * char * term * assignment
19 and assignment = (char * bound_value) list
20 and expressed_value = Int of int | Bool of bool | Pair of expressed_value * expressed_value | Closure of char * term * assignment;;
22 let rec eval (t : term) (g : assignment) = match t with
23 Intconstant x -> Int x
24 | Multiplication (t1, t2) ->
25 (* we don't handle cases where the subterms don't evaluate to Ints *)
26 let Int i1 = eval t1 g
27 in let Int i2 = eval t2 g
28 (* Multiplication (t1, t2) should evaluate to an Int *)
30 | Addition (t1, t2) ->
31 let Int i1 = eval t1 g
32 in let Int i2 = eval t2 g
35 (* we don't handle cases where g doesn't bind var to any value *)
36 match List.assoc var g with
37 | Nonrecursive value -> value
38 | Recursive_Closure (self_var, arg_var, body, savedg) as rec_closure ->
39 (* we update savedg to bind self_var to rec_closure here *)
40 let savedg' = (self_var, rec_closure) :: savedg
41 in Closure (arg_var, body, savedg')
43 | Let (var_to_bind, t2, t3) ->
44 (* evaluate t3 under a new assignment where var_to_bind has been bound to
45 the result of evaluating t2 under the current assignment *)
46 let value2 = eval t2 g
47 (* we have to wrap value2 in Nonrecursive *)
48 in let g' = (var_to_bind, Nonrecursive value2) :: g
51 (* we don't handle cases where t1 doesn't evaluate to an Int *)
52 let Int i1 = eval t1 g
53 (* Iszero t1 should evaluate to a Bool *)
56 (* we don't handle cases where t1 doesn't evaluate to a boolean *)
57 let Bool b1 = eval t1 g
58 in if b1 then eval t2 g
60 | Makepair (t1, t2) ->
61 let value1 = eval t1 g
62 in let value2 = eval t2 g
63 in Pair (value1, value2)
65 (* we don't handle cases where t1 doesn't evaluate to a Pair *)
66 let Pair (value1, value2) = eval t1 g
68 | Lambda (arg_var, t2) -> Closure (arg_var, t2, g)
70 (* we don't handle cases where t1 doesn't evaluate to a function value *)
71 let Closure (arg_var, body, savedg) = eval t1 g
72 in let value2 = eval t2 g
73 (* evaluate body under savedg, except with arg_var bound to Nonrecursive value2 *)
74 in let savedg' = (arg_var, Nonrecursive value2) :: savedg
76 | Letrec (var_to_bind, t2, t3) ->
77 (* we don't handle cases where t2 doesn't evaluate to a function value *)
78 let Closure (arg_var, body, savedg) = eval t2 g
79 (* evaluate t3 under a new assignment where var_to_bind has been recursively bound to that function value *)
80 in let g' = (var_to_bind, Recursive_Closure (var_to_bind, arg_var, body, savedg)) :: g