An accumulator is a very simple computer. It contains a single register and a program.
A program is a list of instructions.
When the accumulator runs its program, each instruction is executed.
Executing an instruction updates the register.
Initially, there are two types of instructions: Add(arg) (adds arg to register) and Mul(arg) (multiplies register by arg).
Here's a test driver:
object testAccumulator extends App {
// computing 3 * 4 + 9
Accumulator.program = List(Add(3),
Mul(4), Add(9))
Accumulator.run()
println("register = " +
Accumulator.register)
// computing ((3 * 5) + 1) * 2
Accumulator.program = List(Add(3),
Mul(5), Add(1), Mul(2))
Accumulator.run()
println("register
= " + Accumulator.register)
// computing (((10 * 2) + 3) * 5)
Accumulator.program
= List(Add(10), Mul(2), Add(3), Mul(5))
Accumulator.run()
println("register
= " + Accumulator.register)
Here's the output:
register = 21.0
register = 32.0
register = 115.0
Here's the initial design:
Notes
I am representing singletons as classes with a singleton stereotype.
Implement and test the design.
Add a Halt instruction to the accumulator in instruction set. When executed, program execution immediately stops.
For example:
Accumulator.program = List(Add(3),
Mul(4), Halt(), Add(9))
Accumulator.run()
println("register = " + Accumulator.register)
// prints 12
Hint: Consider adding halt flag to the accumulator.
Add a Rep instruction to the accumulator in instruction set:
When executed, Rep executes its body num times. For example:
Accumulator.program = List(Add(1),
Rep(5, Mul(2)), Add(10))
Accumulator.run()
println("register = " + Accumulator.register) // prints 42
Add a branch-if-less-than instruction to the accumulator in instruction set:
Blt(n, m) // jumps ahead m instructions in the program if register < n
For example:
Accumulator.program = List(Add(1),
Rep(5, Mul(2)), Blt(33, 2),
Add(10), Halt(), Add(10))
Accumulator.run()
println("register = " + Accumulator.register)
// prints 32
Hint: Consider adding an instruction pointer, ip, to the accumulator, where ip
is the index of the next instruction to be excuted.