Homework 10Implementing an ML Interpreter in ML |
Modified: |
In this assignment, we will implement an interpreter for a subset of ML. We have seen that programs, such as machine language programs for the Hypothetical Machine, can be executed or interpreted by other programs. In the case of the Hypothetical Machine, the interpreter modeled the hardware architecture and implemented the fetch/execute cycle of the processor in order to execute programs.
Executing a high-level language requires parsing source text to some intermediate form, such as an Abstract Syntax Tree (AST). Compilers can then translate the AST to machine code; interpreters can execute the program directly from the AST representation. Our implementation will use the AST directly, implying we will enter programs as an AST. For example, the ML:
3+4;
can be represented as an AST for Language Three by:
val3( Plus(Const 3, Const 4), [] );
with the AST graphical representation of:
Plus
/
\
Const 3 Const 4
Language 3 will be extended to implement additional ML language constructs.
Define Language 4, an extension of Language 3. Below is a somewhat contorted ML program using all of the new constructs:
let val fact = fn n => if n=0 or n=1 then 1 else n * fact(n-1)
in
fact 5
end
Language 4 extends Language 3 with four new constructs:
The symbol T may still be defined from a previous assignment. If so, ML will give an error similar to:
Can't unify ('a * 'b) list with BOOL (Different type constructors) Found near
::( ( var, value), T)
The fix is to change any T to some other symbol, t will do, as in the following.
fun lookup (V,(var,value)::t) = if (V=var) then value else lookup(V,t);
| PolyML.Compiler.debug := true; open PolyML.Debug; trace true; datatype AST = |
val4(Sub(Const 5,Const 1),[]); returns 4
val4(Sub(Var "n",Const 1),[("n",Const 5)]); returns 4
val4(Eq(Const 3,Const 4),[]); returns Bool false
val4(Eq(Bool true, Bool false),[]); returns Bool false
val4(Eq(Var "X",Var "Y"),[("Y",Const 4),("X",Const 4)]); returns Bool true
Perform unit level test using:
val4(If(Bool true, Const 3, Const 4),[]); return Const 3
val4(If(Or(Bool true, Bool false), Const 3, Const 4),[]); return Const 3
val4(If(Eq(Const 3,Const 4),Const 1,Const 2),[]); returns 2
val4(If(Eq(Var "A",Var "B"),Var "A",Var "B"),[("A",Const 4),("B",Const 3)]);
returns Const 3
val4(
Let( "fact",
Fn( "n",
If( Or(Eq(Var "n", Const
0),Eq(Var "n", Const 1)),
Const 1,
Times(Var "n", Apply(Var "fact", Sub(Var "n",Const 1))))),
Apply(Var "fact", Const 5)),
[]);