A Stack Machine

A stack machine is a simple computer containing a stack of integer and a program.

A program is a list of commands.

When the stack machine runs, each command in the program is executed.

Most commands update the stack when executed.

There are five commands:

Push(arg)   // pushes arg onto stack

Pop()       // removes the stack's top element

Top()       // prints the stack's top element (without removing it)

Sum()       // replaces the top two elements of the stack by their sum

Times()     // replaces the top two elements of the stack by their product

An exception is thrown if there aren't enough elements on the stack to execute a command.

Here is a sample run:

StackMachine.program = List(Push(3), Push(4), Push(5), Sum(), Times(), Top())
StackMachine.run()                             //> top = 27
  
StackMachine.program = List(Push(10), Push(10), Times(), Push(20), Sum(), Top())
StackMachine.run()                             //> top = 120

Create a worksheet called sm.

Implement StackMachine and any other classes, objects, or traits you may need.

Test your implementation with the samples above.