116 lines
2.6 KiB
Standard ML
116 lines
2.6 KiB
Standard ML
(*
|
|
https://www.smlnj.org/doc/smlnj-lib/Util/str-Atom.html
|
|
https://github.com/smlnj/smlnj/blob/22e7e397c77fdc90a8b38aaba7f99d5c3ab59a7d/smlnj-lib/Util/atom.sml
|
|
Atoms are hashed strings. Looks like:
|
|
|
|
datatype atom = ATOM of {
|
|
hash : word,
|
|
id : string
|
|
}
|
|
|
|
https://www.classes.cs.uchicago.edu/archive/2015/spring/22620-1/ord-map-sig.html
|
|
*)
|
|
signature EXPRSIG =
|
|
sig
|
|
datatype Expr = Const of real
|
|
| Var of Atom.atom
|
|
| Plus of Expr * Expr
|
|
| Mult of Expr * Expr
|
|
| Let of Expr * Expr
|
|
|
|
datatype Stmt = Assign of Atom.atom * Expr
|
|
| Print of Expr
|
|
|
|
type Program = Stmt list
|
|
end
|
|
|
|
structure ExprEval :> EXPRSIG =
|
|
struct
|
|
datatype Expr = Const of real
|
|
| Var of Atom.atom
|
|
| Plus of Expr * Expr
|
|
| Mult of Expr * Expr
|
|
|
|
datatype Stmt = Assign of Atom.atom * Expr
|
|
| Print of Expr
|
|
|
|
type Program = Stmt list
|
|
|
|
|
|
(*
|
|
eval : Env -> Expr -> real option
|
|
*)
|
|
fun eval env (Const c) = SOME c
|
|
| eval env (Var v) = AtomMap.find(env, v)
|
|
| eval env (Plus(a, b)) =
|
|
let
|
|
val aval = (eval env a)
|
|
val bval = (eval env b)
|
|
fun optionPlus (SOME x, SOME y) = SOME (x + y)
|
|
| optionPlus _ = NONE
|
|
in
|
|
optionPlus (aval, bval)
|
|
end
|
|
| eval env (Mult(a, b)) =
|
|
let
|
|
val aval = (eval env a)
|
|
val bval = (eval env b)
|
|
fun optionMult (SOME x, SOME y) = SOME (x * y)
|
|
| optionMult _ = NONE
|
|
in
|
|
optionMult (aval, bval)
|
|
end
|
|
|
|
|
|
fun execute env (Assign(v,e)) =
|
|
let
|
|
val exprval = eval env e
|
|
in
|
|
if (isSome exprval) then
|
|
AtomMap.insert(env, v, valOf exprval)
|
|
else env
|
|
end
|
|
| execute env (Print e) =
|
|
let
|
|
val exprval = eval env e
|
|
val strval = if (isSome exprval) then Real.toString (valOf exprval)
|
|
else ""
|
|
in
|
|
print(strval ^ "\n"); env
|
|
end
|
|
|
|
(*
|
|
(*
|
|
execute : Env -> Stmt -> Env
|
|
*)
|
|
fun execute : Env -> Stmt -> Env
|
|
|
|
(*
|
|
interpret : Program -> ()
|
|
*)
|
|
fun interpret
|
|
|
|
end
|
|
*)
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
(*
|
|
AtomMap.insert(AtomMap.empty, Atom.atom "h", 2);
|
|
val it = - : int AtomRedBlackMap.map
|
|
- AtomMap.listItems (AtomMap.insert(AtomMap.empty, Atom.atom "h", 2));
|
|
val it = [2] : int list
|
|
- val h = AtomMap.insert(AtomMap.empty, Atom.atom "h", 2);
|
|
val h = - : int AtomRedBlackMap.map
|
|
- AtomMap.listItems h;
|
|
val it = [2] : int list
|
|
- AtomMap.insert(h, Atom.atom "h", 22);
|
|
val it = - : int AtomRedBlackMap.map
|
|
- AtomMap.listItems (AtomMap.insert(h, Atom.atom "h", 22));
|
|
val it = [22] : int list
|
|
*)
|