Reverse Polish Notation

Like most programming languages, Postscript code consists of operators and operands.

Consider the arithmatic operation 2 + 3 = 5. The operands are 2 and 3, and the operator is plus (+). In Postscript this same operation would be coded as

2 3 add

The Postscript operation appears to be the reverse of “add 2 and 3.” The reason for this is that Postscipt is a “stack” based language. The numbers 2 and 3 are “pushed” onto the stack and then subsequently “popped” off the stack by the add operator which expected to find its two operands, the integers, on the stack. The result, 5, is then pushed onto the stack waiting invisibly for the next operation.

Another “type” of operand is the string of characters. Where some programming languages might say

PRINT “Hello world!”

Postscript says:

(Hello world!) print

The term Polish in “reverse-polish notation” refers to the fact that operators and operands are kept to one side or another. Postscript finds the operands to the left.

For instance, the common notation (2 + 3) * (4 – 1) is stated in Postscript as:

2 3 add 4 1 sub mul

Notice how the results of add and sub are left waiting invisibly on the stack for the mul operator. And the final result, 15, is also left waiting on the stack.

Another operator, exch, is very useful in Postscript because it exchanges the top two positions on the stack.

4 1 exch sub

results in the number minus three being left on the stack.