1 2 datatype e = 3 Var of string 4 | Num of int 5 | Add of e * e 6 | Assign of string * e; 7 8 datatype t = 9 Dec of string * t 10 | Exp of e 11 | Break 12 | Seq of t * t 13 | If of e * t * t 14 | For of e * e * t; 15 16 datatype r = 17 Rval of int 18 | Rbreak 19 | Rtimeout 20 | Rfail; 21 22 fun lookup y [] = NONE 23 | lookup y ((x,v)::xs) = if y = x then SOME v else lookup y xs 24 25 fun run_e s (Var x) = 26 (case lookup x s of 27 NONE => (Rfail,s) 28 | SOME v => (Rval v,s)) 29 | run_e s (Num i) = (Rval i,s) 30 | run_e s (Add (e1, e2)) = 31 (case run_e s e1 of 32 (Rval n1, s1) => 33 (case run_e s1 e2 of 34 (Rval n2, s2) => (Rval (n1+n2), s2) 35 | r => r) 36 | r => r) 37 | run_e s (Assign (x, e)) = 38 (case run_e s e of 39 (Rval n1, s1) => (Rval n1, (x,n1)::s1) 40 | r => r) 41 42 fun run_t s (Exp e) = run_e s e 43 | run_t s (Dec (x, t)) = run_t ((x,0)::s) t 44 | run_t s Break = (Rbreak, s) 45 | run_t s (Seq (t1, t2)) = 46 (case run_t s t1 of 47 (Rval _, s1) => run_t s1 t2 48 | r => r) 49 | run_t s (If (e, t1, t2)) = 50 (case run_e s e of 51 (Rval n1, s1) => 52 if n1 = 0 then 53 run_t s1 t2 54 else 55 run_t s1 t1 56 | r => r) 57 | run_t s (For (e1, e2, t)) = 58 (case run_e s e1 of 59 (Rval n1, s1) => 60 if n1 = 0 then (Rval 0, s1) else 61 (case run_t s1 t of 62 (Rval _, s2) => 63 (case run_e s2 e2 of 64 (Rval _, s3) => run_t s3 (For (e1, e2, t)) 65 | r => r) 66 | (Rbreak, s2) => 67 (Rval 0, s2) 68 | r => r) 69 | r => r) 70