Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Finished required sections of assignment, including comments.
  • Loading branch information
ars13025 committed Jan 30, 2018
1 parent 95038cc commit 32a6f6f
Showing 1 changed file with 26 additions and 10 deletions.
36 changes: 26 additions & 10 deletions Homework_1.sml
Expand Up @@ -2,38 +2,54 @@
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};

(*Getters and Setters*)
(*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);

datatype Instruction = SetA of int | SetB of int | Add | Sub | Disp;
(*Converts Instruction to a string*)
(*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*)
fun eval (m: MachineState, SetA a) : MachineState = m;
| eval (m: MachineState, SetB b): MachineState = m;
| eval (m: MachineState, Add) : MachineState = m;
| eval (m: MachineState, Sub) : MachineState = m;
(*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 the list of Instructions*)
(*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 print (i2s instr ^ "\n");
in
run (m1: MachineState, tl prog : Instruction list)
end;

0 comments on commit 32a6f6f

Please sign in to comment.