Course of Raku / Advanced / Operators / User-defined operators / Exercises / A squaring operator

Solution: A squaring operator

Here is a possible solution to the task.

Code

sub postfix:<²>($x) {
    $x ** 2
}

say 5²;

🦋 You can find the source code in the file square-operator.raku.

Output

25

Comments

  1. The operator is declared as postfix:<²>, so its symbol — the superscript-two character — is written after its operand, as in .

  2. The body raises the operand to the power of two, so evaluates to 25. Nothing stops you from using a Unicode symbol that mirrors the mathematical notation.

Course navigation

A squaring operator   |   Quiz — Defining an operator