Permalink
Cannot retrieve contributors at this time
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?
CSE4102-HW1/Homework_1.sml
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
55 lines (45 sloc)
1.81 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(* | |
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; |