From 32a6f6f6ea270b9e0a87ea322a62215de48c2701 Mon Sep 17 00:00:00 2001 From: Ashley Sanders Date: Tue, 30 Jan 2018 14:08:41 -0500 Subject: [PATCH] Finished required sections of assignment, including comments. --- Homework_1.sml | 36 ++++++++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/Homework_1.sml b/Homework_1.sml index bba3520..d703178 100644 --- a/Homework_1.sml +++ b/Homework_1.sml @@ -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; \ No newline at end of file