/
operators.pod6
3620 lines (2540 loc) · 122 KB
/
operators.pod6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
=begin pod :kind("Language") :subkind("Language") :category("fundamental")
=TITLE Operators
=SUBTITLE Common Raku infixes, prefixes, postfixes, and more!
See L<creating operators|/language/optut> on how to define new operators.
=head1 Operator precedence
The precedence and associativity of Raku operators determine the order of
evaluation of operands in expressions.
Where two operators with a different precedence act on the same operand, the
subexpression involving the higher-precedence operator is evaluated first. For
instance, in the expression C<1 + 2 * 3>, both the binary C<+> operator for
addition and the binary C<*> operator for multiplication act on the operand
C<2>. Because the C<*> operator has a higher precedence than the C<+> operator,
the subexpression C<2 * 3> will be evaluated first. Consequently, the resulting
value of the overall expression is C<7> and not C<9>.
Instead of "precedence" one can also speak of "binding": operators with a higher
precedence are then said to have a tighter binding to the operand(s) in
question, while operators with a lower precedence are said to have a looser
binding. In practice one may also encounter blends of terminology, such as
statements that an operator has a tighter or looser precedence.
Where two operators with a same precedence level act on an operand, the
associativity of the operators determines which subexpression/operator is
evaluated first. For instance, in the expression C<100 / 2 * 10>, the binary
division operator C</> and the binary multiplication operator C<*> have equal
precedence, so that the order of their evaluation is determined by their
associativity. As the two operators are I<left associative>, operations are
grouped from the left like this: C<(100 / 2) * 10>. The expression thus
evaluates to C<500>, rather than to C<5>.
The following table summarizes the precedence levels (column labeled C<Level>)
offered by Raku, listing them in order from high to low precedence. For each
precedence level the table also indicates the associativity of the operators
assigned to that level (column labeled C<A>), and some exemplary operators
(column labeled C<Examples>).
=begin table
A | Level | Examples
==+==================+==========
N | Terms | 42 3.14 "eek" qq["foo"] $x :!verbose @$array rand time now ∅
L | Method postfix | .meth .\+ .? .* .() .[] .{} .<> .«» .:: .= .^ .:
N | Autoincrement | \+\+ --
R | Exponentiation | **
L | Symbolic unary | ! \+ - ~ ? \| \|\| \+^ ~^ ?^ ^
L | Dotty infix | .= .
L | Multiplicative | * × / ÷ % %% \+& \+< \+> ~& ~< ~> ?& div mod gcd lcm
L | Additive | \+ - − \+\| \+^ ~\| ~^ ?\| ?^
L | Replication | x xx
X | Concatenation | ~ o ∘
X | Junctive and | & (&) (.) ∩ ⊍
X | Junctive or | \| ^ (\|) (^) (\+) (-) ∪ ⊖ ⊎ ∖
L | Named unary | temp let
N | Structural infix | but does <=> leg unicmp cmp coll .. ..^ ^.. ^..^
C | Chaining infix | != ≠ == < <= ≤ > >= ≥ eq ne lt le gt ge ~~ === eqv !eqv =~= ≅ (elem) (cont) (<) (>) (<=) (>=) (<\+) (>\+) ∈ ∉ ∋ ∌ ⊂ ⊄ ⊃ ⊅ ⊆ ⊈ ⊇ ⊉ ≼ ≽
X | Tight and | &&
X | Tight or | \|\| ^^ // min max
R | Conditional | ?? !! ff ff^ ^ff ^ff^ fff fff^ ^fff ^fff^
R | Item assignment | = => \+= -= **= xx=
L | Loose unary | so not
X | Comma operator | , :
X | List infix | Z minmax X X~ X* Xeqv ... … ...^ …^ ^... ^… ^...^ ^…^
R | List prefix | print push say die map substr ... [\+] [*] any Z=
X | Loose and | and andthen notandthen
X | Loose or | or xor orelse
X | Sequencer | <==, ==>, <<==, ==>>
N | Terminator | ; {...}, unless, extra ), ], }
=end table
The following table further clarifies the meaning of the associativity symbols
(C<L R N C X>) specified above in column C<A>. Using a fictitious C<!> binary
operator symbol, it shows how each associativity affects the interpretation of
an expression involving two such operators of equal precedence:
=begin table
A | Assoc | Meaning of $a ! $b ! $c
===+=========+========================
L | left | ($a ! $b) ! $c
R | right | $a ! ($b ! $c)
N | non | ILLEGAL
C | chain | ($a ! $b) and ($b ! $c)
X | list | infix:<!>($a; $b; $c)
=end table
For unary operators generically represented by a C<!> symbol, the
associativities C<L R N> lead to the following interpretations:
=begin table
A | Assoc | Meaning of !$a!
===+=========+==========================
L | left | (!$a)!
R | right | !($a!)
N | non | ILLEGAL
=end table
In the operator descriptions below, a default associativity of I<left>
is assumed.
=head1 Operator classification
X<|prefix operator>
X<|infix operator>
X<|postfix operator>
X<|circumfix operator>
X<|postcircumfix operator>
X<|method operators>
Operators can occur in several positions relative to a term:
=begin table
\+term | prefix
term1 \+ term2 | infix
term\+\+ | postfix
(term) | circumfix
term1[term2] | postcircumfix
.+(term) | method
=end table
Each operator (except method operators) is also available as a subroutine. The
name of the routine is formed from the operator category, followed by a colon,
then a list quote construct with the symbol(s) that make up the operator:
infix:<+>(1, 2); # same as 1 + 2
circumfix:«[ ]»(<a b c>); # same as [<a b c>]
As a special case, a I<listop> (list operator) can stand either as a
term or as a prefix. Subroutine calls are the most common listops. Other
cases include metareduced infix operators (C<[+] 1, 2, 3>) and the
L<#prefix ...> etc. stub operators.
Defining custom operators is covered in
L<Defining operators functions|/language/functions#Defining_operators>.
=head1 Metaoperators
Metaoperators can be parameterized with other operators or subroutines
in the same way as functions can take functions as parameters. To use a
subroutine as a parameter, prefix its name with a C<&>. Raku will
generate the actual combined operator in the background, allowing the
mechanism to be applied to user defined operators. To disambiguate
chained metaoperators, enclose the inner operator in square brackets.
There are quite a few metaoperators with different semantics as
explained, next.
=head1 Substitution operators
Each substitution operator comes into two main forms: a lowercase one (e.g.,
C<s///>) that performs I<in-place> (i.e., I<destructive> behavior; and an
uppercase form (e.g., C<S///>) that provides a I<non-destructive> behavior.
=head2 X«C<s///> in-place substitution»
my $str = 'old string';
$str ~~ s/o .+ d/new/;
say $str; # OUTPUT: «new string»
C<s///> operates on the C<$_> topical variable, changing it in
place. It uses the given
L«C<Regex>|/type/Regex» to find portions to replace and changes them to the
provided replacement string. Sets C<$/> to the L«C<Match>|/type/Match» object
or, if multiple matches were made, a L«C<List>|/type/List» of C<Match> objects.
Returns C<$/>.
It's common to use this operator with the C<~~> smartmatch operator, as it
aliases left-hand side to C<$_>, which C<s///> uses.
Regex captures can be referenced in the replacement part; it takes the same
adverbs as the L«C<.subst> method|/routine/subst», which go between the C<s>
and the opening C</>, separated with optional whitespace:
my $str = 'foo muCKed into the lEn';
# replace second 'o' with 'x'
$str ~~ s:2nd/o/x/;
# replace 'M' or 'L' followed by non-whitespace stuff with 'd'
# and lower-cased version of that stuff:
$str ~~ s :g :i/<[ML]> (\S+)/d{lc $0}/;
say $str; # OUTPUT: «fox ducked into the den»
You can also use a different delimiter:
my $str = 'foober';
$str ~~ s!foo!fox!;
$str ~~ s{b(.)r} = " d$0n";
say $str; # OUTPUT: «fox den»
Non-paired characters can simply replace the original slashes. Paired
characters, like curly braces, are used only on the match portion, with the
substitution given by assignment (of anything: a string, a routine call, etc.).
=head2 X«C<S///> non-destructive substitution»
say S/o .+ d/new/ with 'old string'; # OUTPUT: «new string»
S:g/« (.)/$0.uc()/.say for <foo bar ber>; # OUTPUT: «FooBarBer»
C<S///> uses the same semantics as the C<s///> operator, except
it leaves the original string intact
and I<returns the resultant string> instead of C<$/> (C<$/> still being set
to the same values as with C<s///>).
B<Note:> since the result is obtained as a return value, using this
operator with the C<~~> smartmatch operator is a mistake and will issue a
warning. To execute the substitution on a variable that isn't the C<$_> this
operator uses, alias it to C<$_> with C<given>, C<with>, or any other way.
Alternatively, use the L«C<.subst> method|/routine/subst».
=head2 X«C<tr///> in-place transliteration»
my $str = 'old string';
$str ~~ tr/dol/wne/;
say $str; # OUTPUT: «new string»
C<tr///> operates on the C<$_> topical variable and changes it in place.
It behaves similar to
L«C<Str.trans>|/routine/trans» called with a single L<Pair|/type/Pair> argument, where
key is the matching part (characters C<dol> in the example above) and value is
the replacement part (characters C<wne> in the example above). Accepts the
same adverbs as L«C<Str.trans>|/routine/trans». Returns the L<StrDistance|/type/StrDistance> object
that measures the distance between original value and the resultant string.
my $str = 'old string';
$str ~~ tr:c:d/dol st//;
say $str; # OUTPUT: «old st»
=head2 X«C<TR///> non-destructive transliteration»
with 'old string' {
say TR/dol/wne/; # OUTPUT: «new string»
}
C<TR///> behaves the same as the C<tr///> operator,
except that it leaves the C<$_>
value untouched and instead returns the resultant string.
say TR:d/dol // with 'old string'; # OUTPUT: «string»
=head1 Assignment operators
Raku has a variety of assignment operators, which can be roughly classified as
simple assignment operators and compound assignment operators.
The simple assignment operator symbol is C<=>. It is 'overloaded' in the sense
that it can mean either L<item
assignment|/language/operators#infix_=_(item_assignment)> or L<list
assignment|/language/operators#infix_=_(list_assignment)> depending on the
context in which it is used:
my $x = 1; # item assignment; $x = 1
my @x = 1,2,3; # list assignment; @x = [1,2,3]
See the section on L<item and list
assignment|/language/variables#Item_and_list_assignment> for a more elaborate
and comparative discussion of these two types of assignment.
The compound assignment operators are
L<metaoperators|/language/operators#Metaoperators>: they combine the simple
assignment operator C<=> with an infix operator to form a new operator that
performs the operation specified by the infix operator before assigning the
result to the left operand. Some examples of built-in compound assignment
operators are C<+=>, C<-=>, C<*=>, C</=>, C<min=>, and C<~=>. Here is how they
work:
my $a = 32;
$a += 10; # $a = 42
$a -= 2; # $a = 40
$a = 3;
$a min= 5; # $a = 3
$a min= 2; # $a = 2
my $s = 'a';
$s ~= 'b'; # $s = 'ab'
# And an example of a custom operator:
sub infix:<space-concat> ($a, $b) { $a ~ " " ~ $b };
my $a = 'word1';
$a space-concat= 'word2'; # OUTPUT: «'word1 word2'»
One thing the simple and compound assignment operators have in common is that
they form so-called I<assignment expressions> that return or evaluate to the
assigned value:
my sub fac (Int $n) { [*] 1..$n }; # sub for calculating factorial
my @x = ( my $y = fac(100), $y*101 ); # @x = [100!, 101!]
my $i = 0;
repeat { say $i } while ($i += 1) < 10; # OUTPUT: «0,1,2,...9»
In the first example, the assignment expression C<my $y = fac(100)> declares
C<$y>, assigns the value C<fac(100)> to it, and finally returns the assigned
value C<fac(100)>. The returned value is then taken into account for
constructing the List. In the second example the compound-assignment expression
C<$i += 1> assigns the value C<$i + 1> to C<$i>, and subsequently evaluates to
the assigned value C<$i+1>, thus allowing the returned value to be used for
judging the while loop condition.
In dealing with simple and compound assignment operators, it is tempting to
think that for instance the following two statements are (always) equivalent:
=for code :skip-test<pseudo code>
expression1 += expression2; # compound assignment
expression1 = expression1 + expression2; # simple assignment
They are not, however, for two reasons. Firstly, C<expression1> in the compound
assignment statement is evaluated only once, whereas C<expression1> in the
simple assignment statement is evaluated twice. Secondly, the compound
assignment statement may, depending on the infix operator in question,
implicitly initialize C<expression1> if it is a variable with an undefined
value. Such initialization will not occur for C<expression1> in the simple
assignment statement.
The aforementioned two differences between the simple and compound assignment
statements are briefly elucidated below.
The first difference is common amongst programming languages and mostly
self-explanatory. In the compound assignment, there is only one C<expression1>
that is explicitly specified to serve both as a term of the addition to be
performed and as the location where the result of the addition, the sum, is to
be stored. There is thus no need to evaluate it twice. The simple assignment, in
contrast, is more generic in the sense that the value of the C<expression1> that
serves as a term of the addition need not necessarily be the same as the value
of the C<expression1> that defines the location where the sum must be stored.
The two expressions are therefore evaluated separately. The distinction is
particularly relevant in cases where the evaluation of C<expression1> has side
effects in the form of changes to one or more variables:
my @arr = [10, 20, 30];
my $i = 0;
if rand < 1/2 {
@arr[++$i] += 1; # @arr = [10,21,30]
} else {
@arr[++$i] = @arr[++$i] + 1; # @arr = [10,31,30] (or [10,20,21]?)
} # the result may be implementation-specific
say @arr;
The second difference pointed out above is related to the widespread practice of
using compound assignment operators in I<accumulator patterns>. Such patterns
involve a so-called I<accumulator>: a variable that calculates the sum or a
product of a series of values in a loop. To obviate the need for explicit
accumulator initialization, Raku's compound assignment operators silently take
care of the initialization where this is sensibly possible:
my @str = "Cleanliness is next to godliness".comb;
my ($len, $str);
for @str -> $c {
$len += 1;
$str ~= $c;
}
say "The string '$str' has $len characters.";
In this example the accumulators C<$len> and C<$str> are implicitly initialized
to C<0> and C<"">, respectively, which illustrates that the initialization value
is operator-specific. In this regard it is also noted that not all compound
assignment operators can sensibly initialize an undefined left-hand side
variable. The C</=> operator, for instance, will not arbitrarily select a value
for the dividend; instead, it will throw an exception.
Although not strictly operators, methods can be used in the same fashion as
compound assignment operators:
my $a = 3.14;
$a .= round; # $a = $a.round; OUTPUT: «3»
=head1 Negated relational operators
X<|! (negation metaoperator)>X<|!==>X<|!eq>
The result of a relational operator returning C<Bool> can be negated by
prefixing with C<!>. To avoid visual confusion with the C<!!> operator,
you may not modify any operator already beginning with C<!>.
There are shortcuts for C<!==> and C<!eq>, namely C<!=> and C<ne>.
my $a = True;
say so $a != True; # OUTPUT: «False»
my $i = 10;
my $release = Date.new(:2015year, :12month, :24day);
my $today = Date.today;
say so $release !before $today; # OUTPUT: «False»
=head1 Reversed operators
X<|R,reverse metaoperator>
Any infix operator may be called with its two arguments reversed by
prefixing with C<R>. Associativity of operands is reversed as well.
say 4 R/ 12; # OUTPUT: «3»
say [R/] 2, 4, 16; # OUTPUT: «2»
say [RZ~] <1 2 3>,<4 5 6> # OUTPUT: «(41 52 63)»
X<|»=«>
X<|«=»>
=head1 X<<<Hyper operators|hyper,<<;hyper,>>;hyper,«;hyper,»;>>>
Hyper operators include C<«> and C<»>, with their ASCII variants C«<<» and
C«>>». They apply a given operator enclosed (or preceded or followed, in the
case of unary operators) by C<«> and/or C<»> to one or two lists, returning the
resulting list, with the pointy part of C<«> or C<»> aimed at the shorter list.
Single elements are turned to a list, so they can be used too. If one of the
lists is shorter than the other, the operator will cycle over the shorter list
until all elements of the longer list are processed.
say (1, 2, 3) »*» 2; # OUTPUT: «(2 4 6)»
say (1, 2, 3, 4) »~» <a b>; # OUTPUT: «(1a 2b 3a 4b)»
say (1, 2, 3) »+« (4, 5, 6); # OUTPUT: «(5 7 9)»
say (&sin, &cos, &sqrt)».(0.5);
# OUTPUT: «(0.479425538604203 0.877582561890373 0.707106781186548)»
The last example illustrates how postcircumfix operators (in this case .()) can
also be hypered.
my @a = <1 2 3>;
my @b = <4 5 6>;
say (@a,@b)»[1]; # OUTPUT: «(2 5)»
In this case, it's the L<postcircumfix[]|/language/operators#circumfix_[_]> which is being hypered.
Assignment metaoperators can be I<hyped>.
my @a = 1, 2, 3;
say @a »+=» 1; # OUTPUT: «[2 3 4]»
my ($a, $b, $c);
(($a, $b), $c) «=» ((1, 2), 3);
say "$a, $c"; # OUTPUT: «1, 3»
Hyper forms of unary operators have the pointy bit aimed at the operator and
the blunt end at the list to be operated on.
my @wisdom = True, False, True;
say !« @wisdom; # OUTPUT: «[False True False]»
my @a = 1, 2, 3;
@a»++;
say @a; # OUTPUT: «[2 3 4]»
Hyper operators are defined recursively on nested arrays.
say -« [[1, 2], 3]; # OUTPUT: «[[-1 -2] -3]»
Also, methods can be called in an out of order, concurrent fashion. The
resulting list will be in order. Note that all hyper operators are candidates
for parallelism and will cause tears if the methods have side effects. The
optimizer has full reign over hyper operators, which is the reason that they
cannot be defined by the user.
class CarefulClass { method take-care {} }
my CarefulClass @objs;
my @results = @objs».take-care();
my @slops; # May Contain Nuts
@slops».?this-method-may-not-exist();
Hyper operators can work with hashes. The pointy direction indicates if missing
keys are to be ignored in the resulting hash. The enclosed operator operates on
all values that have keys in both hashes.
=begin table
%foo «+» %bar; intersection of keys
%foo »+« %bar; union of keys
%outer »+» %inner; only keys of %inner that exist in %outer will occur in the result
=end table
my %outer = 1, 2, 3 Z=> <a b c>;
my %inner = 1, 2 Z=> <x z>;
say %outer «~» %inner; # OUTPUT: «{"1" => "ax", "2" => "bz"}»
Hyper operators can take user-defined operators as their operator argument.
sub pretty-file-size (Int $size --> Str) {
# rounding version of infix:</>(Int, Int)
sub infix:<r/>(Int \i1, Int \i2) {
round(i1 / i2, 0.1)
}
# we build a vector of fractions of $size and zip that with the fitting prefix
for $size «[r/]« (2**60, 2**50, 2**40, 2**30, 2**20, 2**10)
Z <EB PB TB GB MB KB> -> [\v,\suffix] {
# starting with the biggest suffix,
# we take the first that is 0.5 of that suffix or bigger
return v ~ ' ' ~ suffix if v > 0.4
}
# this be smaller or equal then 0.4 KB
return $size.Str;
}
for 60, 50, 40, 30, 20, 10 -> $test {
my &a = { (2 ** $test) * (1/4, 1/2, 1, 10, 100).pick * (1..10).pick };
print pretty-file-size(a.Int) xx 2, ' ';
}
# OUTPUT: «10 EB 4 EB 2 PB 5 PB 0.5 PB 4 TB 300 GB 4.5 GB 50 MB 200 MB 9 KB 0.6 MB»
Whether hyperoperators descend into child lists depends on the
L<nodality|/language/typesystem#trait_is_nodal> of the inner operator of a
chain. For the hyper method call operator (».), the nodality of the target
method is significant.
say (<a b>, <c d e>)».elems; # OUTPUT: «(2 3)»
say (<a b>, <c d e>)».&{ .elems }; # OUTPUT: «((1 1) (1 1 1))»
You can chain hyper operators to destructure a List of Lists.
my $neighbors = ((-1, 0), (0, -1), (0, 1), (1, 0));
my $p = (2, 3);
say $neighbors »>>+<<» ($p, *); # OUTPUT: «((1 3) (2 2) (2 4) (3 3))»
X<|[] (reduction metaoperators)>X<|[+] (reduction metaoperators)>
=head1 Reduction metaoperators
The reduction metaoperator, C<[ ]>, reduces a list with the given infix
operator. It gives the same result as the L<reduce|/routine/reduce> routine -
see there for details.
# These two are equivalent:
say [+] 1, 2, 3; # OUTPUT: «6»
say reduce &infix:<+>, 1, 2, 3; # OUTPUT: «6»
No whitespace is allowed between the square brackets and the operator. To wrap a
function instead of an operator, provide an additional layer of square brackets:
sub plus { $^a + $^b };
say [[&plus]] 1, 2, 3; # OUTPUT: «6»
The argument list is iterated without flattening. This means that you can pass
a nested list to the reducing form of a list infix operator:
say [X~] (1, 2), <a b>; # OUTPUT: «(1a 1b 2a 2b)»
which is equivalent to C«1, 2 X~ <a b>».
X<|[\] (triangular reduction metaoperators)>
By default, only the final result of the reduction is returned. Prefix the
wrapped operator with a C<\>, to return a lazy list of all intermediate values
instead. This is called a "triangular reduce". If the I<non-meta> part
contains a
C<\> already, quote it with C<[]> (e.g. C<[\[\x]]>).
my @n = [\~] 1..*;
say @n[^5]; # OUTPUT: «(1 12 123 1234 12345)»
=head1 Cross operators
X<|X (cross metaoperator)>
The cross metaoperator, C<X>, will apply a given infix operator in order of
cross product to all lists, such that the rightmost operand varies most
quickly.
1..3 X~ <a b> # OUTPUT: «<1a, 1b, 2a, 2b, 3a, 3b>»
=head1 Zip metaoperator
X<|Z (zip metaoperator)>
The zip metaoperator (which is not the same thing as L<Z|#infix_Z>) will
apply a given infix operator to pairs taken one left, one right, from its
arguments. The resulting list is returned.
my @l = <a b c> Z~ 1, 2, 3; # OUTPUT: «[a1 b2 c3]»
If one of the operands runs out of elements prematurely, the zip operator will
stop. An infinite list can be used to repeat elements. A list with a final
element of C<*> will repeat its 2nd last element indefinitely.
my @l = <a b c d> Z~ ':' xx *; # OUTPUT: «<a: b: c: d:>»
@l = <a b c d> Z~ 1, 2, *; # OUTPUT: «<a1 b2 c2 d2>»
If an infix operator is not given, the C<,> (comma operator) will be used by
default:
my @l = 1 Z 2; # OUTPUT: «[(1 2)]»
=head1 Sequential operators
X<|S,sequential metaoperator>
The sequential metaoperator, C<S>, will suppress any concurrency or reordering
done by the optimizer. Most simple infix operators are supported.
say so 1 S& 2 S& 3; # OUTPUT: «True»
=head1 Nesting of metaoperators
To avoid ambiguity when chaining metaoperators, use square brackets to help the
compiler understand you.
my @a = 1, 2, 3;
my @b = 5, 6, 7;
@a X[+=] @b;
say @a; # OUTPUT: «[19 20 21]»
=head1 Z<>Term precedence
=head2 term C«< >»
The X<quote-words|qw;quote-words> construct breaks up the contents on whitespace
and returns a L<List|/type/List> of the words. If a word looks like a number
literal or a C<Pair> literal, it's converted to the appropriate number.
say <a b c>[1]; # OUTPUT: «b»
=head2 term C«( )»
The X<grouping operator>.
An empty group C<()> creates an L<empty list|/type/List#index-entry-()_empty_list>.
Parentheses around non-empty expressions simply structure the expression, but do
not have additional semantics.
In an argument list, putting parenthesis around an argument prevents it from
being interpreted as a named argument.
multi sub p(:$a!) { say 'named' }
multi sub p($a) { say 'positional' }
p a => 1; # OUTPUT: «named»
p (a => 1); # OUTPUT: «positional»
=head2 term C«{ }»
L<Block|/type/Block> or L<Hash|/type/Hash> constructor.X<|block constructor;hash constructor>
If the content is empty, or contains a single list that starts with a L<Pair|/type/Pair>
literal or C<%>-sigiled variable, and the L«C<$_> variable|/syntax/$_» or
placeholder parameters are not used, the constructor returns a L<Hash|/type/Hash>.
Otherwise it constructs a L<Block|/type/Block>.
To force construction of a L<Block|/type/Block>, follow the opening brace with a semicolon.
To always ensure you end up with a L<Hash|/type/Hash>, you can use C<%( )> coercer or
L<hash|/routine/hash> routine instead:
{}.^name.say; # OUTPUT: «Hash»
{;}.^name.say; # OUTPUT: «Block»
{:$_}.^name.say; # OUTPUT: «Block»
%(:$_).^name.say; # OUTPUT: «Hash»
hash(:$_).^name.say; # OUTPUT: «Hash»
=head2 circumfix C«[ ]»
The X<L<Array|/type/Array> constructor> returns an itemized L<Array|/type/Array> that does not flatten
in list context. Check this:
say .raku for [3,2,[1,0]]; # OUTPUT: «32$[1, 0]»
This array is itemized, in the sense that every element constitutes an item, as
shown by the C<$> preceding the last element of the array, the
L<(list) item contextualizer|/type/Any#index-entry-%24_%28item_contextualizer%29>.
=head1 Terms
Terms have their L<own extended documentation|/language/terms>.
=head1 Method postfix precedence
=head2 postcircumfix C«[ ]»
sub postcircumfix:<[ ]>(@container, **@index,
:$k, :$v, :$kv, :$p, :$exists, :$delete)
Universal interface for positional access to zero or more elements of a
@container, a.k.a. "X<array indexing operator|array indexing operator;array subscript operator>".
my @alphabet = 'a' .. 'z';
say @alphabet[0]; # OUTPUT: «a»
say @alphabet[1]; # OUTPUT: «b»
say @alphabet[*-1]; # OUTPUT: «z»
say @alphabet[100]:exists; # OUTPUT: «False»
say @alphabet[15, 4, 17, 11].join; # OUTPUT: «perl»
say @alphabet[23 .. *].raku; # OUTPUT: «("x", "y", "z")»
@alphabet[1, 2] = "B", "C";
say @alphabet[0..3].raku; # OUTPUT: «("a", "B", "C", "d")»
See L<Subscripts|/language/subscripts>, for a more detailed explanation of this
operator's behavior and for how to implement support for it in custom types.
=head2 postcircumfix C«{ }»
sub postcircumfix:<{ }>(%container, **@key,
:$k, :$v, :$kv, :$p, :$exists, :$delete)
Universal interface for associative access to zero or more elements of a
%container, a.k.a. "X<hash indexing operator|hash indexing operator;hash subscript operator>".
my %color = kiwi => "green", banana => "yellow", cherry => "red";
say %color{"banana"}; # OUTPUT: «yellow»
say %color{"cherry", "kiwi"}.raku; # OUTPUT: «("red", "green")»
say %color{"strawberry"}:exists; # OUTPUT: «False»
%color{"banana", "lime"} = "yellowish", "green";
%color{"cherry"}:delete; # note that value is always returned but removal only happens when delete is true.
say %color; # OUTPUT: «banana => yellowish, kiwi => green, lime => green»
See L«C«postcircumfix < >»|/routine/< >#(Operators)_postcircumfix_<_>» and
L<C<postcircumfix « »>|/routine/« »#(Operators)_postcircumfix_«_»> for convenient
shortcuts, and L<Subscripts|/language/subscripts> for a more detailed
explanation of this operator's behavior and how to implement support for it
in custom types.
=head2 postcircumfix C«<>»
Decontainerization operator, which extracts the value from a container and makes
it independent of the container type.
=begin code
use JSON::Tiny;
my $config = from-json('{ "files": 3, "path": "/home/some-user/raku.pod6" }');
say $config.raku; # OUTPUT: «${:files(3), :path("/home/some-user/raku.pod6")}»
my %config-hash = $config<>;
say %config-hash.raku; # OUTPUT: «{:files(3), :path("/home/some-user/raku.pod6")}»
=end code
It's a C<Hash> in both cases, and it can be used like that; however, in the
first case it was in item context, and in the second case it has been extracted
to its proper context.
=head2 postcircumfix C«< >»
Shortcut for L<C<postcircumfix { }>|/routine/{ }#(Operators)_postcircumfix_{_}>
that quotes its argument using the same rules as the L«quote-words operator|
/routine/< >#circumfix_<_>» of the same name.
my %color = kiwi => "green", banana => "yellow", cherry => "red";
say %color<banana>; # OUTPUT: «yellow»
say %color<cherry kiwi>.raku; # OUTPUT: «("red", "green")»
say %color<strawberry>:exists; # OUTPUT: «False»
Technically, not a real operator; it's syntactic sugar that's turned into the
C<{ }> postcircumfix operator at compile-time.
=head2 postcircumfix C<« »>
Shortcut for L<C<postcircumfix { }>|/routine/{ }#(Operators)_postcircumfix_{_}>
that quotes its argument using the same rules as the
L<interpolating quote-words operator|/language/quoting#Word_quoting_with_interpolation_and_quote_protection:_«_»>
of the same name.
my %color = kiwi => "green", banana => "yellow", cherry => "red";
my $fruit = "kiwi";
say %color«cherry "$fruit"».raku; # OUTPUT: «("red", "green")»
Technically, not a real operator; it's syntactic sugar that's turned into the
C<{ }> postcircumfix operator at compile-time.
=head2 postcircumfix C«( )»
The X<call operator> treats the invocant as a L<Callable|/type/Callable> and invokes it,
using the expression between the parentheses as arguments.
Note that an identifier followed by a pair of parentheses is always parsed as a
subroutine call.
If you want your objects to respond to the call operator,
implement a L«C<method CALL-ME>|/routine/CALL-ME».
=head2 methodop C«.»
The operator for calling one method, C<$invocant.method>.X<|method call>
Technically, not a real operator; it's syntax special-cased in the compiler.
X«|methodop .&»
=head2 methodop C«.&»
The operator to call a subroutine (with at least one positional argument), such
as a method. The invocant will be bound to the first positional argument.
Technically, not a real operator; it's syntax special-cased in the compiler.
my sub f($invocant){ "The arg has a value of $invocant" }
42.&f;
# OUTPUT: «The arg has a value of 42»
42.&(-> $invocant { "The arg has a value of $invocant" });
# OUTPUT: «The arg has a value of 42»
=head2 methodop C«.=»
A X<mutating method call>. C<$invocant.=method> desugars to
C<$invocant = $invocant.method>, similar to L<=|/routine/=> .
Technically, not a real operator; it's syntax special-cased in the compiler.
X«|methodop .^»
=head2 methodop C«.^»
A X<metamethod call>. C<$invocant.^method> calls C<method> on C<$invocant>'s
metaclass. It desugars to C<$invocant.HOW.method($invocant, ...)>. See
L<the metaobject protocol documentation|/language/mop> for more information.
Technically, not a real operator; it's syntax special-cased in the compiler.
It can be also applied, within classes, to access metamethods on self:
=for code
class Foo {
has $.a = 3;
method bar {
return $.^name
}
};
say Foo.new.bar; # OUTPUT: «Foo»
X«|methodop .?»
=head2 methodop C«.?»
X<Safe call operator>. C<$invocant.?method> calls method C<method> on
C<$invocant> if it has a method of such name. Otherwise it returns
L<Nil|/type/Nil>.
Technically, not a real operator; it's syntax special-cased in the compiler.
X«|methodop .+»
=head2 methodop C«.+»
C<$foo.+meth> walks the L<MRO|/language/objects#index-entry-MRO> and calls all the methods called C<meth> and
submethods called C<meth> if the type is the same as type of C<$foo>. Those
methods might be multis, in which case the matching candidate would be called.
After that, a L<List|/type/List> of the results are returned. If no such method
was found, it throws a L<X::Method::NotFound|/type/X::Method::NotFound> exception.
class A {
method foo { say "from A"; }
}
class B is A {
multi method foo { say "from B"; }
multi method foo(Str) { say "from B (Str)"; }
}
class C is B is A {
multi method foo { say "from C"; }
multi method foo(Str) { say "from C (Str)"; }
}
say C.+foo; # OUTPUT: «from Cfrom Bfrom A(True True True)»
X«|methodop .*»
=head2 methodop C«.*»
C<$foo.*meth> walks the L<MRO|/language/objects#index-entry-MRO> and calls all the methods called C<meth> and
submethods called C<meth> if the type is the same as type of C<$foo>. Those
methods might be multis, in which case the matching candidate would be called.
After that, a L<List|/type/List> of the results are returned. If no such method
was found, an empty L<List|/type/List> is returned.
Technically, postfix C<.+> calls C<.*> at first. Read postfix C<.+> section to
see examples.
X<|methodop ».>X«|methodop >>.»
=head2 methodop C<».> / methodop C«>>.»
This is the X<hyper method call operator>. Will call a method on all elements of
a C<List> out of order and return the list of return values in order.
=for code
my @a = <a b c>;
my @b = @a».ord; # OUTPUT: «[97, 98, 99]»
# The first parameter of a method is the invocant.
sub foo(Str:D $c){ $c.ord * 2 };
# So we can pretend to have a method call with a sub that got a good
# first positional argument.
say @a».&foo;
# Blocks have an implicit positional arguments that lands in $_. The latter can
# be omitted for method calls.
say @a».&{ .ord};
Hyper method calls may appear to be the same as doing a L<map|/routine/map>
call, however along with being a hint to the compiler that it can parallelize
the call, the behavior is also affected by L<nodality of the
method|/routine/is%20nodal> being invoked, depending on which either
L<nodemap|/routine/nodemap> or L<deepmap|/routine/deepmap> semantics are used to
perform the call.
The nodality is checked by looking up whether the L<Callable|/type/Callable>
provides C<nodal> method. If the hyper is applied to a method, that
L<Callable|/type/Callable> is that method name, looked up on L<List|/type/List>
type; if the hyper is applied to a routine (e.g. C<».&foo>), that routine
functions as that L<Callable|/type/Callable>. If the L<Callable|/type/Callable>
is determined to provide C<nodal> method, L<nodemap|/routine/nodemap> semantics
are used to perform the hyper call, otherwise L<duckmap|/routine/duckmap>
semantics are used.
Take care to avoid a
L<common mistake|/language/traps#Using_»_and_map_interchangeably> of expecting
side-effects to occur in order. The following C<say> is B<not>
guaranteed to produce the output in order:
=begin code :preamble<my @a>
@a».say; # WRONG! Could produce abc or cba or any other order
=end code
X<|.( )>X<|.[ ]>X<|.{ }>
=head2 methodop C<.postfix> / C<.postcircumfix>
In most cases, a dot may be placed before a postfix or postcircumfix:
my @a;
@a[1, 2, 3];
@a.[1, 2, 3]; # Same
This can be useful for visual clarity or brevity. For example, if an object's
attribute is a function, putting a pair of parentheses after the attribute name
will become part of the method call. So, either two pairs of parentheses must be
used or a dot has to come before the parentheses to separate it from the method
call.
class Operation {
has $.symbol;
has &.function;
}
my $addition = Operation.new(:symbol<+>, :function{ $^a + $^b });
say $addition.function()(1, 2); # OUTPUT: «3»
# OR
say $addition.function.(1, 2); # OUTPUT: «3»
If the postfix is an identifier, however, it will be interpreted as a normal
method call.
=begin code
1.i # No such method 'i' for invocant of type 'Int'
=end code
Technically, not a real operator; it's syntax special-cased in the compiler.
X<|postfix operator call>
=head2 methodop C«.:<prefix operator>»
An operator in prefix form can still be called like a method, that is, using the
C<.> methodop notation, by preceding it by a colon. For example:
my $a = 1;
say ++$a; # OUTPUT: «2»
say $a.:<++>; # OUTPUT: «3»
Technically, not a real operator; it's syntax special-cased in the compiler,
that is why it's classified as a I<methodop>.
=head2 methodop C«.::»
A X<class-qualified method call>, used to call a method as defined in a parent
class or role, even after it has been redefined in the child class.
class Bar {
method baz { 42 }
}
class Foo is Bar {
method baz { "nope" }
}
say Foo.Bar::baz; # OUTPUT: «42»
=head2 postfix C<,=>
Creates an object that concatenates, in a class-dependent way, the contents of
the variable on the left hand side and the expression on the right hand side:
my %a = :11a, :22b;
%a ,= :33x;
say %a # OUTPUT: «{a => 11, b => 22, x => 33}»
=head1 Autoincrement precedence
X<|prefix increment operator>
=head2 prefix X<C«++»|prefix ++>
multi sub prefix:<++>($x is rw) is assoc<non>
Increments its argument by one and returns the updated value.
my $x = 3;
say ++$x; # OUTPUT: «4»
say $x; # OUTPUT: «4»
It works by calling the L<succ|/routine/succ> method (for I<successor>) on its
argument, which gives custom types the freedom to implement their own increment
semantics.
X<|prefix decrement operator>
=head2 prefix X<C«--»|prefix -->
multi sub prefix:<-->($x is rw) is assoc<non>
Decrements its argument by one and returns the updated value.