I’m working on assignment 2 of CS193P – Stanford’s IOS programming course. One thing I was wondering about is how the calculatorBrain is supposed to be able to accept and run a stored program, a program being an array or stack of operands and operations.
So let’s say we want to perform the following calculation: 2, 3, 4, +, *
If you typed this into the calulator, the following would happen:
2 3 4 get pushed onto the stack one at a time, and runProgram called for each one, which simply pops the number off the stack and returns it’s value which gets pushed onto the stack.
You press +, and runProgram pops this and sees it has to add the top 2 items which it does and pushes the result onto the stack which now contains 2, 7. You press * and the stack now contains 14.
But I can’t see how you can pass an array containing (2, 3, 4, +, *) to the brain (the instructor says later you can just pass a program to the runProgram class method and get the result, without having to instantiate a brain object), as runProgram would first try to execute the top operand i.e. * and to do this it would take the next two objects off the stack and try to multiply them and to push the result back onto the stack. These 2 objects are “+” and “4” which won’t work.
Now the instructor has been doing this a lot longer than I have, as I assume that I’m missing somethings, but I’m not sure what.
Any ideas?
OK – the answer is that the way runProgram gets the next item off the stack is by recursively calling a popOperandOffStack (pOOS) method.
So when it gets passed a program consisting of 2 3 4 + *, it starts by popping * off the stack. It then has to pop the next two operands off the stack. So it calls pOOS, which firstly returns a ‘+’, so it then calls pOOS again (twice) which gets ‘4’ & ‘3’ respectively, which are added to get 7 which is pushed back onto the stack (which now contains 2 7) and also returned as the result of calling pOOS. So when it called pOOS for the first operand of the ‘*’ operation it didn’t get ‘+’, it actually got ‘7’. The second call to pOOS (for the second operand of the *) gets ‘2’ which it then happily multiplies to get 14.
I did try looking up recursion in my IT dictionary, but it just said ‘See recursion’.