🌍 Pangea / Pang

Understanding Polish (Prefix) Notation

What is Polish Notation?

Polish notation, invented by Polish logician Jan Łukasiewicz in 1924, is a mathematical notation where operators precede their operands. In computer science, this is called prefix notation.

Comparison: Infix vs Prefix

Infix (Standard) Prefix (Polish) Result
5 + 6 + 5 6 11
3 * 4 * 3 4 12
(2 + 3) * 4 * + 2 3 4 20
2 + 3 * 4 + 2 * 3 4 14

Key Advantages

1. No Parentheses Needed

The structure is unambiguous without grouping symbols.

Infix:

((5 + 6) * (7 - 2))

Prefix:

* + 5 6 - 7 2

2. No Operator Precedence Rules

You don't need to remember that multiplication comes before addition.

3. Easy to Parse

Left-to-right evaluation with simple recursive descent.

Reading Polish Notation

The key is understanding arity - how many arguments each operator takes:

Expression: + 5 6

+ ← Operator (arity: 2)
5 ← First argument
6 ← Second argument

Result: 11

Complex Example Walkthrough

Let's evaluate: multiply add 2 3 subtract 10 5

Step-by-Step Evaluation

Initial State

multiply add 2 3 subtract 10 5

multiply needs 2 arguments, so we evaluate the next two expressions.

Step 1: Evaluate first argument (add 2 3)

multiply add 2 3 subtract 10 5

add 2 3 β†’ 5

Step 2: Evaluate second argument (subtract 10 5)

multiply 5 subtract 10 5

subtract 10 5 β†’ 5

Step 3: Final multiplication

multiply 5 5

multiply 5 5 β†’ 25

Final Result: 25

Parse Tree Visualization

Polish notation creates a natural tree structure:

Γ— + βˆ’ 2 3 10 5

Expression: multiply add 2 3 subtract 10 5

Polish Notation in Pangea

Pangea extends basic Polish notation with named operations:

// Instead of: + 5 6
add 5 6

// Instead of: * + 2 3 - 10 5
multiply add 2 3 subtract 10 5

// With variables and control flow
set x 10
if greater x 5
    print " x is large "
    print " x is small "

Why Use Polish Notation?

βœ“ Consistency

Every expression follows the same pattern: operation arg1 arg2 ... argN

βœ“ Extensibility

Easy to add new operations without worrying about precedence.

βœ“ Simplicity

No need for complex parsing rules or ambiguity resolution.

βœ“ Natural for Functional Programming

Functions as first-class operators fit naturally.

⚠ Trade-off: Readability

While unambiguous and consistent, Polish notation can be less intuitive for humans accustomed to mathematical infix notation. However, with practice, it becomes natural.

Practice Examples

Try to evaluate these in your head:

1. add multiply 2 3 4

Show answer

multiply 2 3 = 6
add 6 4 = 10

2. multiply add 1 2 add 3 4

Show answer

add 1 2 = 3
add 3 4 = 7
multiply 3 7 = 21

3. subtract multiply 5 5 multiply 3 3

Show answer

multiply 5 5 = 25
multiply 3 3 = 9
subtract 25 9 = 16

πŸŽ“ Next Step

Now that you understand Polish notation, learn how Pangea evaluates expressions using recursive descent and phrase length calculation.