Just trying to follow Peter-Sulzer's post on stack calculations, and `EJC'.
Learning from the Wiki, we have so called `infix' and `postfix' notations. The latter sometimes called `reversed Polish' e.g. found implemented on HP calculators, also the idea of `FORTH' programming language.
Infix formula as we know from normal maths.
Code: Select all
5 * ( 6 + 2 ) - 12 / 4
Code: Select all
5 6 2 + * 12 4 / -
As Postfix is easy to evaluate, using Push(), Pop(), the idea is to convert Infix formula into Postfix first.
Infix-To-Postfix notation conversion pseudo code
Code: Select all
Start with an empty stack.
We scan Infix expression `Q' from left to right, and we produce `P' postfix formula from it.
While (we have not reached the end of Q)
If (an operand is found)
Add it to P
End-If
If (a left parenthesis is found)
Push it onto the stack
End-If
If (a right parenthesis is found)
While (the stack is not empty AND the top item is not a left parenthesis)
Pop the stack and add the popped value to P
End-While
Pop the left parenthesis from the stack and discard it
End-If
If (an operator is found)
If (the stack is empty or if the top element is a left parenthesis)
Push the operator onto the stack
Else
While (the stack is not empty AND the top of the stack
is not a left parenthesis AND precedence of the
operator <= precedence of the top of the stack)
Pop the stack and add the top value to P
End-While
Push the latest operator onto the stack
End-If
End-If
End-While
While (the stack is not empty)
Pop the stack and add the popped value to P
End-While
It would be interesting to know, how this is handled by QL arithmetic stack, as Super BASIC interpreter must do something similar for us?
TODO postfix formula evaluation is easier, I will copy in the next post.
Tomas