chapter1.sml 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. type id = string
  2. type table = (id * int) list
  3. datatype binop = Plus | Minus | Times | Div
  4. datatype stm = CompoundStm of stm * stm
  5. | AssignStm of id * exp
  6. | PrintStm of exp list
  7. and exp = IdExp of id
  8. | NumExp of int
  9. | OpExp of exp * binop * exp
  10. | EseqExp of stm * exp
  11. val prog =
  12. CompoundStm ( AssignStm ( "a",
  13. OpExp ( NumExp 5, Plus, NumExp 3 ) ),
  14. CompoundStm ( AssignStm ( "b",
  15. EseqExp ( PrintStm [ IdExp "a",
  16. OpExp ( IdExp "a",
  17. Minus,
  18. NumExp 1 ) ],
  19. OpExp ( NumExp 10,
  20. Times,
  21. IdExp "a" ))),
  22. PrintStm [ IdExp "b" ]))
  23. fun maxoflist [] = 0
  24. | maxoflist (x::xs) = Int.max (x, maxoflist xs)
  25. fun maxargs s =
  26. let fun maxargs_exp e =
  27. case e of
  28. IdExp _ => 0
  29. | NumExp _ => 0
  30. | OpExp (e1, _, e2) => Int.max (maxargs_exp e1, maxargs_exp e2)
  31. | EseqExp (s, e1) => Int.max (maxargs s, maxargs_exp e1)
  32. in
  33. case s of
  34. PrintStm l => Int.max (List.length l, maxoflist (map maxargs_exp l))
  35. | AssignStm (_, e) => maxargs_exp e
  36. | CompoundStm (s1, s2) => Int.max (maxargs s1, maxargs s2)
  37. end
  38. fun fst (a,_) = a
  39. fun snd (_,b) = b
  40. fun lookup (k:id) ([]:table) = 0
  41. | lookup k ((i,v)::ts) = if k = i
  42. then v
  43. else lookup k ts
  44. fun update (t:table) (i:id,v) = (i,v)::t
  45. fun interpStm (t:table) (CompoundStm (s1, s2)) = interpStm (interpStm t s1) s2
  46. | interpStm t (PrintStm l) = (print (String.concatWith " " (map (expAsStr t) l));
  47. print "\n";
  48. t)
  49. | interpStm t (AssignStm (i, e)) =
  50. let
  51. val (t1,v1) = interpExp t e
  52. in
  53. update t1 (i, v1)
  54. end
  55. and interpExp (t:table) (NumExp x) = (t, x)
  56. | interpExp t (IdExp k) = (t, lookup k t)
  57. | interpExp t (EseqExp (s,e)) = (interpExp (interpStm t s) e)
  58. | interpExp t (OpExp (a1,oper,a2)) =
  59. let
  60. val (t1,v1) = interpExp t a1
  61. val (t2,v2) = interpExp t1 a2
  62. in case oper of
  63. Plus => (t2, (v1 + v2))
  64. | Minus => (t2, (v1 - v2))
  65. | Times => (t2, (v1 * v2))
  66. | Div => (t2, Int.div (v1, v2))
  67. end
  68. and expAsStr t (NumExp x) = Int.toString x
  69. | expAsStr t (IdExp a) = Int.toString (lookup a t)
  70. | expAsStr t (OpExp x) =
  71. let
  72. val (t1,v1) = interpExp t (OpExp x)
  73. in
  74. Int.toString v1
  75. end
  76. | expAsStr t (EseqExp (s,e)) = expAsStr (interpStm t s) e
  77. fun interp s = interpStm [] s