(* Mandatory exercise 1, INF3110/4110, 2007 *) (* A solution suggestion *) (* datatype declarations *) (* We declare a specific type for variable names *) datatype var = I | J | K ; (* datatype declarations for expressions *) datatype exp = Num of int | Var of var | Pluss of exp * exp ; datatype boolexp = Bool of exp * exp ; (* datatype declarations for statements *) datatype stmt = IfThen of boolexp * stmt | Assign of var * exp | Print of exp ; (* the datatype for program *) type prog = stmt list ; (* program state *) (* 1: The state or memory is just a record type *) type state = { i : int , j : int , k : int } ; fun getVal(x:var, s:state):int = case x of I => #i s | J => #j s | K => #k s ; fun putVal(x:var, n:int, s:state):state = case x of I => {i=n , j=(#j s) , k=(#k s)} | J => {i=(#i s) , j=n, k=(#k s)} | K => {i=(#i s) , j=(#j s) , k=n} ; fun stateToStr({ i : int , j : int , k : int }) = "{i="^Int.toString(i)^", j="^Int.toString(j)^", k="^Int.toString(k)^"}\n"; (* initial state with i=j=k=0 *) val init = {i=0,j=0,k=0} ; (* ML representation of the sample program *) val sampleprog = [ Assign(I,Num(1)) , Assign(J,Num(2)) , Assign(K,Pluss(Var(I),Var(J))) , IfThen(Bool(Var(K),Num(3)),Print(Var(K))) ] ; fun printIntNL(i) = print(Int.toString(i)^"\n") ; (* evaluation of an expression in a state *) fun evalExp(exp,s):int = case exp of Num(i) => i | Var(v) => getVal(v,s) | Pluss(exp,exp') => evalExp(exp,s) + evalExp(exp',s) ; (* evaluation of bool expression *) fun evalBool(Bool(ex,ex'),s) = evalExp(ex,s) = evalExp(ex',s) ; (* evaluation of a statement in a state *) fun eval(st:stmt, s:state):state = case st of IfThen(b,st') => if evalBool(b,s) then eval(st',s) else s | Assign(v,exp) => putVal(v,evalExp(exp,s),s) | Print(exp) => ( printIntNL(evalExp(exp,s)) ; s ) ; (* the interpret function *) fun interpret(p:prog,s:state):state = case p of [] => s | p'::ps => interpret(ps,eval(p',s)); (* code to test your implementation *) (print "(*** Program start ***)\n"; print ("Initial state: \t"^(stateToStr(init))); print ("Final state: \t"^(stateToStr(interpret(sampleprog,init)))); print "(*** Program end ***)\n");