A stack machine is a stack of doubles 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
Mul() // 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:
object StackMachineDemo extends App {
StackMachine.program = List(Push(2), Push(3),
Push(4), Add(), Mul(), Top())
StackMachine.execute()
StackMachine.program = List(Push(2), Push(3),
Add(), Mul(), Top())
StackMachine.execute()
}
Here's the output:
top = 14.0
empty collection
Here's a fragment of the design:

Implement and test the design.