REVERSE POLISH NOTATION

advertisement
REVERSE POLISH NOTATION
One common technique in syntax analysis is the conversion of arithmetic assignment
statements into a ‘Reverse Polish Notation (RPN). It not only provides a syntax check on
the expression but also generates an alternative form of the statement more suited to
code generation.
Arithmetic statements can be expressed in a form similar to the following statement in
BASIC:
X = A * (B + C) / D
If this were to be carried out in a one-address code or pocket calculator then the series
of operation would be:
LOAD
ADD
MULTIPLY
DIVIDE
STORE
B
C
A
D
X
The standard notation is called ‘infix’ notation with the operators placed between the
operands e.g. (B+C). In RPN the above expression would be expressed as:
XABC+*D/=
The operators are always given after the operand, hence the expression ‘postfix’
notation.
Expressions in postfix notation can be evaluated according to the following rules:
1.
Scan the expression left to right
2.
Apply each operator in turn to the two operands that precede it
3.
The result of each operation is to be regarded as a single operand
The evaluation of X A B C + * D / = will thus be:
add B to C
multiply the result by A
divide that result by D
store the result in X
A special symbol ~ is used to show negative numbers (called the unary minus). –A-B would
be shown as A~BConvert the following to postfix:
1. (A+B)*(C-D)
4. A*B+C^D
2/ X*Y*Z-W
5. 2*(3*X+1)^3
3. W/X+2*Y
6. Y=(X*B)/(W-Z)
7. P=Q*(S-T^U)
8. A=(-X+C^E)*Y
9. X=(-W+A*(5*Y-Z^3))/2
convert the following to infix:
1. uv/wxy+*-z2. x3^y3z+^*
3. abc*de*+ac*fe*-/=
Download