(* CL EVALUATOR & INTERPRETER *) (* REPRESENTATION OF STORES *) datatype store = Store of (variable -> value); (* INITIAL STORE - everything mapped to 0 *) val init_store = Store(fn v => Intval 0); local (* STORE OPERATIONS *) fun fetch(x,Store f) = f x; fun update(Store f, x, v) = Store(fn y => if y=x then v else f y); (* AUXILIARY PRINT FUNCTION *) local (* print out one integer or boolean value *) fun printone (Intval n) = print n |printone (Boolval b) = print b in (*** print out a list of arguments - one per line ***) fun printargs nil = () |printargs (a::x) = (printone a; print "\n"; printargs x) end in (* EVALUATOR *) fun evalexp (IConstant n) s = Intval n |evalexp (BConstant b) s = Boolval b |evalexp (Contents v) s = fetch(v,s) |evalexp (Plus(e1,e2)) s = let val Intval n1 = evalexp e1 s and Intval n2 = evalexp e2 s in Intval (n1+n2) end |evalexp (Minus(e1,e2)) s = let val Intval n1 = evalexp e1 s and Intval n2 = evalexp e2 s in Intval (n1-n2) end |evalexp (Times(e1,e2)) s = let val Intval n1 = evalexp e1 s and Intval n2 = evalexp e2 s in Intval (n1*n2) end |evalexp (Greater(e1,e2)) s = let val Intval n1 = evalexp e1 s and Intval n2 = evalexp e2 s in Boolval(n1 > n2) end; (* INTERPRETER *) fun interpret (Assign(v,e)) s = update(s,v,(evalexp e s)) |interpret (Sequence(c1,c2)) s = interpret c2 (interpret c1 s) |interpret (Conditional(e,c1,c2)) s = let val Boolval(b) = evalexp e s in interpret (if b then c1 else c2) s end |interpret (Loop as While(e,c)) s = let val Boolval(b) = evalexp e s in if b then interpret (Sequence(c, Loop)) s else s end |interpret (Print(args)) s = let val _ = printargs (map (fn e=> evalexp e s) args) in s end; end;