Operators
Custom operators
FullDefine your own prefix, infix, and postfix operators as ordinary subs.
Operators in Raku are just subs with special names. Declaring sub infix:<…>, prefix:<…>, or postfix:<…> adds a new operator to the language — usable with the same syntax as the built-ins, Unicode symbols included.
A postfix operator #
The name postfix:<!> defines ! after its operand — here, factorial.
sub postfix:<!>($n) { [*] 1..$n }
say 5!;
Output
120An infix operator #
sub infix:<×>($a, $b) { $a * $b }
say 6 × 7;
Output
42A prefix operator #
sub prefix:<√>($x) { $x.sqrt }
say √16;
Output
4Notes #
- The three slots are
prefix(before),postfix(after), andinfix(between); there is alsocircumfix(like⟨ ⟩) andpostcircumfix(like[ ]). - Operator names can be any symbol run, ASCII or Unicode, so
×,√, and∘are all valid. - Give a custom infix a precedence with a trait —
is tighter(&infix:<+>),is looser(...), oris equiv(...)— otherwise it defaults to the tightest.