Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
(*
Homework 1: Simple Register Machine
By: Ashley Sanders
*)
(*Used to store the values of the two registers: a and b*)
type MachineState = {a:int, b:int};
(*May contain the value of any defined instruction*)
datatype Instruction = SetA of int | SetB of int | Add | Sub | Disp;
(*Creates a new MachineState with the given initial values*)
fun newMachine (a, b) : MachineState = {a=a, b=b};
(*Gets the current value of a in the given MachineState*)
fun getA (m : MachineState) = #a m;
(*Gets the current value of b in the given MachineState*)
fun getB (m : MachineState) = #b m;
(*Sets the value of a in the given MachineState*)
fun setA (m : MachineState, newA) = newMachine(newA, #b m);
(*Sets the value of b in the given MachineState*)
fun setB (m : MachineState, newB) = newMachine(#a m, newB);
(*Converts an Instruction to a string for ease of printing values*)
fun i2s (SetA a) = "SetA " ^ Int.toString(a)
| i2s (SetB b) = "SetB " ^ Int.toString(b)
| i2s Add = "Add"
| i2s Sub = "Sub"
| i2s Disp = "Disp";
(*Evaluates the given Instruction based on the given MachineState*)
fun eval (m: MachineState, SetA a) : MachineState =
(setA (m, a))
| eval (m: MachineState, SetB b): MachineState =
(setB (m, b))
| eval (m: MachineState, Add) : MachineState =
(newMachine(getA (m) + getB (m), getB (m)))
| eval (m: MachineState, Sub) : MachineState =
(newMachine(getA (m) - getB (m), getB (m)))
| eval (m: MachineState, Disp) : MachineState =
(print (Int.toString (#a m) ^ "\n"); m);
(*Runs and prints the given list of Instructions*)
fun run (m: MachineState, []: Instruction list) = m
| run (m: MachineState, prog: Instruction list) =
let val instr = hd prog
val instrs = tl prog
val _ = print (i2s instr ^ "\n");
val m1 = eval (m, instr);
in
run (m1: MachineState, tl prog : Instruction list)
end;