2. What is an operator?
“Operators are just subroutines with funny names.”
Perl6 Functions Docs : https://docs.perl6.org/language/functions#Defining_operators
4. Creating an operator
Creating the operator OP as different types :
● Infix : sub infix:<OP> ($a, $b) { … } for $a OP $b
● Prefix : sub prefix:<OP> ($a) { … } for OP $a
● Postfix : sub postfix:<OP> ($a) { … } for $aOP
● Circumfix : sub circumfix:<O P> ($a) { … } for O $a P
● Postcircumfix : sub postcircumfix:<O P> (@a, $b) { … } for @aO $b P
Note : Postfix and postcircumfix operators can’t have space between the operand and the operator
5. Operator Overloading
Most operators are defined as multi rather than single subs making overloading
them for different types simple.
role Vector2d {
has Rat $.x;
has Rat $.y;
}
multi infix:<+> (Vector2d $v1, Vector2d $v2) {
Vector2d.new( x => $v1.x + $v2.x, y => $v1.y + $v2.y );
}
Note : You probably want a BUILD submethod to allow for non Rational numbers.
6. Precedence
multi sub infix:<d> (Int $count, Int $size) {
[+] (1..$size).roll($count)
}
say 1 d 6 * 100;
578 ????
multi sub infix:<d> is tighter(&infix:<*>) (Int $count, Int $size) {
[+] (1..$size).roll($count)
}
say 1 d 6 * 100;
300 !!!!
8. Associativity
multi sub infix:<d> is tighter(&infix:<*>) (Int $count, Int $size) {
note “$count d $size”;
[+] (1..$size).roll($count);
}
say 1 d 3 d 6;
“1 d 3” “1 d 6” 3
multi sub infix:<d> is tighter(&infix:<*>) is assoc<right> (Int $count, Int $size) {
note “$count d $size”;
[+] (1..$size).roll($count);
}
say 1 d 3 d 6;
“3 d 6” “1 d 12” 7
9. Associativity options
$a OP $b OP $c
● left : ($a OP $b) OP $c
● right : $a OP ($b OP $c)
● non : Compile time error
● chain : ($a OP $b) and ($b OP $c)
● list : &infix:<OP>( $a, $b, $c )
Note : left is default
10. Metaoperators
● Assignment = : $a OP= $b same as $a = $a OP $b
● Reduction [] : [OP] $a, $b, $c same as $a OP $b OP $c
● Zip Z : (1, 2) ZOP (3, 4) same as (1 OP 3, 2 OP 4)
● Cross X : (1, 2) XOP (3, 4) same as (1 OP 3, 1 OP 4, 2 OP 3, 2 OP 4)
● Reverse R : 1 ROP 2 same as 2 OP 1
● Sequence S : 1 SOP 2 SOP 3 always same as 1 OP 2 OP 3
The sequence Metaoperator stops the optimizer rearranging the order of your
operations.
11. Bonus Slide
sub prefix:<👍> ( *@list ) is looser(&infix:<,> ) {
all( @list ).so;
}
say 👍 <Perl 6 is awesome>;
True