# Reverse Polish Notation

Regular readers – and Twitter followers – will know my standard response to fake maths expressions such as $6 \div 2(1+2)$:

The correct answer is “write the bloody thing properly”.

It’s deliberately ambiguous; just because you *can* write something in mathematical notation doesn’t mean you should, and it doesn’t mean you should expect it to have a single correct value.

But this post isn’t about stupid facebook things. (Check out Kyle D Evans’s book if that sort of thing interests you.) It’s about an unambiguous way of writing mathematical expressions, called Reverse Polish Notation (RPN). ((It’s also called Reverse Łukasiewicz Notation, and I could reasonably have put it in the DOME, only I’d have to look up where Ł was alphabetically and shut up I have COVID still.))

The key idea of RPN is to put your operator *afterwards* rather than in-between. Instead of writing $3 + 2$, you write `3 2 +`

.

That means – well, you can probably work out what it means, but let’s be a bit more systematic: you’re going to keep a stack of numbers. If you reach a number, you put it on the top of the stack; if you reach an operator, you remove the top two numbers on the stack, apply the operator to then and put the resulting number on top of the stack. At the end, you should end up with one number, which is your result. Here, you start with 3 on the stack; you then put 2 on top of the three; then you remove the 2 and 3, add them and put 5 on top of the (now empty) stack. That’s your answer.

There are a couple of wrinkles:

- Some operations depend on order; I’ll adopt the convention that the top number on the stack goes second, so
`2 3 -`

is -1 and`3 4 ^`

is 81. - Not every string of numbers and symbols is valid; as well as division by 0 and
`0 0 ^`

problems, you might also run out of numbers before you hit an operation, or end up with several numbers at the end. As a necessary condition, counting from the left, there must always be more numbers than operators, and in total there must be one more number than operator.

There are many neat things about this system, one of which is that you don’t need brackets any more. For example, the two possible interpretations of the original fake maths expression would be:

`6 2 1 2 + * /`

, meaning “do the division last of all”`6 2 / 1 2 + *`

, meaning “do $6\div 2$ and do the multiplication last”.

RPN takes a little while to get the hang of reading, but it can be extended to work with more complicated functions (and, I would imagine, loops and conditionals – it wouldn’t surprise me if RPN was Turing-complete). I’m not sure I’d advocate replacing conventional notation with it, but if it’s a choice between that and being tagged in yet another stupid “engagement-seeker”, I’d vote RPN every time.