Course of Raku / Advanced / Operators

Review of operator behaviour

When an expression contains several operators, Raku has to decide in what order to apply them. Two rules govern this: precedence and associativity.

Precedence

Precedence decides which operator binds more tightly. Multiplication has higher precedence than addition, so it happens first:

say 2 + 3 * 4; # 14

The expression is read as 2 + (3 * 4), giving 14 rather than 20. You can always use parentheses to force a different order:

say (2 + 3) * 4; # 20

Associativity

Associativity decides the order between operators of the same precedence. Subtraction is left-associative, so it groups from the left:

say 8 - 3 - 2; # 3

This is (8 - 3) - 2, which is 3. Exponentiation, on the other hand, is right-associative:

say 2 ** 3 ** 2; # 512

Here the expression groups as 2 ** (3 ** 2), that is 2 ** 9, which is 512.

Chained comparisons

Comparison operators can be chained, which reads naturally and does what you expect from mathematics:

say 1 < 2 < 3; # True
say 1 < 5 < 3; # False

The middle value is compared with both neighbours: 1 < 2 < 3 is true because 1 < 2 and 2 < 3 are both true.

Practice

Complete the quiz that covers the contents of this topic.

Exercises

This section contains 3 exercises. Examine all the topics of this section before doing the coding practice.

  1. Force the order
  2. Power tower
  3. Chained comparison

Course navigation

Quiz — A word operator   |   Force the order