Stack machine is a processor that uses stack data structure to store operands. Here we are going to implement a simple interpreter first and gradually adding new features we and up with something interesting.
Our interpreter consumes two types of commands:
For this program we need to use effects:
State for storing a List of operands and pushing back results
Halts in case if there are not enough operands to perform an operaton
We either immediately push a value to the stack or evaluate an operation. Operation instruction consumes two operands by taking topmost values from the stack, evaluate operation itself and push result back to the stack. Yes, we are going to use methods of Stack interface here:
As an example, we can provide a sequence of commands that should be performed without errors: