Reverse Polish Notation


 * This page was adapted almost wholly from the English Wikipedia article by the same title, http://en.wikipedia.org/wiki/Reverse_Polish_Notation.

Reverse Polish notation (or just RPN) by analogy with the related Polish notation, a prefix notation introduced in 1920 by the Polish mathematician Jan Łukasiewicz, is a mathematical notation wherein every operator follows all of its operands. It is also known as Postfix notation.

Explanation
In Reverse Polish notation the operators follow their operands; for instance, to add three and four one would write "3 4 +" rather than "3 + 4". If there are multiple operations, the operator is given immediately after its second operand; so the expression written "3 − 4 + 5" in conventional infix notation would be written "3 4 − 5 +" in RPN: first subtract 4 from 3, then add 5 to that. An advantage of RPN is that it obviates the need for parentheses that are required by infix. While "3 − 4 * 5" can also be written "3 − (4 * 5)", that means something quite different from "(3 − 4) * 5", and only the parentheses disambiguate the two meanings. In postfix, the former would be written "3 4 5 * −", which unambiguously means "3 (4 5 *) −".

Interpreters of Reverse Polish notation are often stack-based; that is, operands are pushed onto a stack, and when an operation is performed, its operands are popped from a stack and its result pushed back on. Stacks, and therefore RPN, have the advantage of being easy to implement and very fast.

Note that, despite the name, reverse Polish notation is not exactly the reverse of Polish notation, because for a non-commutative operation the operands are still written in the conventional order (e.g. "6 3 /" in reverse Polish corresponds to "/ 6 3" in Polish notation, these both evaluating to 2). Numbers are of course also written with the digits in the conventional order.

The postfix algorithm
The algorithm for evaluating any postfix expression is fairly straightforward:
 * While there are input tokens left
 * Read the next token from input.
 * If the token is a value
 * Push it onto the stack.
 * Otherwise, the token is a function. (Operators, like +, are simply functions taking two arguments.)
 * It is known that the function takes n arguments.
 * If there are fewer than n values on the stack
 * (Error) The user has not input sufficient values in the expression.
 * Else, Pop the top n values from the stack.
 * Evaluate the function, with the values as arguments.
 * Push the returned results, if any, back onto the stack.
 * If there is only one value in the stack
 * That value is the result of the calculation.
 * If there are more values in the stack
 * (Error) The user input too many values.