• AVincentInSpace@pawb.social
    link
    fedilink
    English
    arrow-up
    1
    ·
    edit-2
    1 year ago

    Here’s a practical explanation of RPN.

    Take the simple expression 1 + 1. The plus sign is between the two operands; this is called infix notation and it’s what you’re probably familiar with. If we wanted to make this more complex, e.g. 1+(2*3), we’d need parentheses to say which part was supposed to be done first.

    Reverse Polish Notation (RPN) means you write the two operands and then the operator, i.e. 1 1 +. Writing more complex equations is as simple as putting another expression in place of one of the numbers: 1 2 3 * +. To see how you’d evaluate this without any parentheses, imagine that as you go through an RPN expression from left to right, you keep a stack of sheets of paper, each with a number written on it, that starts out empty. As you go through, you see:

    • 1, put that on top of the stack
    • 2, put that on top of the stack
    • 3, put that on top of the stack (from top to bottom, the stack is now 3, 2, 1)
    • multiply, take the top two numbers on the stack (2 and 3), multiply them, and put the result back on the stack (the stack now has two numbers, 6 on the top and 1 on the bottom)
    • add, take the top two numbers on the stack, add them, and put the result back (the stack now only has one number on it: 7)

    If we wanted to rewrite that expression to be (1+2)*3 instead, we could write: 1 2 + 3 *

    Simply by reordering the symbols, we change the meaning of the expression, so there’s never any need for parentheses.

    As a bonus, this method of writing equations is a lot easier for computers to parse than infix notation, since they think in terms of stacks anyway. They can be (and often are) programmed to parse infix notation anyway, because infix notation is a lot easier for humans to wrap their brains around, but it’s much easier to program them to interpret RPN which is why a lot of older calculators and software (like the programming language FORTH) use RPN exclusively.

    Let me know if that explanation made sense.