-
Notifications
You must be signed in to change notification settings - Fork 292
/
subscripts.pod6
1000 lines (720 loc) · 38.3 KB
/
subscripts.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 :tag<perl6>
=TITLE Subscripts
=SUBTITLE Accessing data structure elements by index or key
Often one needs to refer to a specific element (or specific slice of
elements) of a collection or data structure. Borrowing from mathematical
notation where the components of a vector I<v> would be referred to as
I<v₁, v₂, v₃>, this concept is called "subscripting" (or "indexing") in
Perl 6.
=head1 Basics
Perl 6 provides two universal subscripting interfaces:
=begin table
elements are interface supported by
identified by name
=== ================== ============= ============================
[ ] zero-based indices Positional Array, List, Buf, Match, ...
{ } string or object keys Associative Hash, Bag, Mix, Match, ...
=end table
=begin item1
B<Positional> subscripting (via L<C<postcircumfix [ ]>|/language/operators#postcircumfix_[_]>)
addresses elements of an ordered collection by their position. Index 0
refers to the first element, index 1 to the second, and so on:
my @chores = "buy groceries", "feed dog", "wash car";
say @chores[0]; # OUTPUT: «buy groceries»
say @chores[1]; # OUTPUT: «feed dog»
say @chores[2]; # OUTPUT: «wash car»
=end item1
=begin item1
B<Associative> subscripting (via L<C<postcircumfix { }>|
/language/operators#postcircumfix_{_}>), does not require the collection to
keep its elements in any particular order - instead, it uses a unique key to
address each value. The nature of the keys depends on the collection in
question: For example a standard L<Hash> uses string keys, whereas a L<Mix>
allows arbitrary objects as keys, etc.:
my %grade = Zoe => "C", Ben => "B+";
say %grade{"Zoe"}; # OUTPUT: «C»
say %grade{"Ben"}; # OUTPUT: «B+»
my $stats = ( Date.today => 4.18, Date.new(2015, 4, 5) => 17.253 ).Mix;
say $stats{ Date.new(2015, 4, 4) + 1 }; # OUTPUT: «17.253»
For passing single-word string keys to C<{ }>, you can also use the
L<angle-bracketed word quoting constructs|/language/quoting#Word_quoting:_qw>
as if they were postcircumfix operators:
my %grade = Zoe => "C", Ben => "B+";
say %grade<Zoe>; # OUTPUT: «C»
say %grade<Ben>; # OUTPUT: «B+»
This is really just syntactic sugar that gets turned into the corresponding
C<{ }> form at compile-time:
=begin code
%hash<foo bar>; # same as %hash{ <foo bar> }
%hash«foo "$var"»; # same as %hash{ «foo "$var"» }
%hash<<foo "$var">>; # same as %hash{ <<foo "$var">> }
=end code
You may have noted above that we avoided having to quote C<Zoe> by using
the C<< => >> operator, but that same operator did not just put invisible
quotes around C<Date.new(2015, 4, 5)>, and we were able to find the
same element using C<$stats{ Date.new(2015, 4, 4) + 1 }>. This is because
C<< => >> only puts invisible quotes around single words, and by "word" we
mean an identifier/name. The C<< => >> operator is there to prevent us from
accidentally calling functions or using constants with that name.
Hash subscripts do not do the same thing as C<< => >>. The default C<Hash>
has been made to behave the way new users have come to expect
from using other languages, and for general ease of use. On a
default C<Hash>, subscripts coerce keys into strings, as long as
those keys produce something C<Cool>. You can use C<.perl> on a
collection to be sure whether the keys are strings or objects:
( 1 => 1 ).perl.say; # OUTPUT: «1 => 1»
my %h; %h{1} = 1; say %h.perl; # OUTPUT: «{ "1" => 1 }»
( 1/2 => 1 ).perl.say; # OUTPUT: «0.5 => 1»
my %h; %h{1/2} = 1; say %h.perl; # OUTPUT: «{ "0.5" => 1 }»
( pi => 1 ).perl.say; # OUTPUT: «:pi(1)»
my %h; %h{pi} = 1; say %h.perl; # OUTPUT: «{ "3.14159265358979" => 1 }»
While the invisible quotes around single names is built into C<< => >>,
string conversion is not built into the curly braces: it is a behavior
of the default C<Hash>. Not all types of hashes or collections
do so:
my %h := MixHash.new;
%h{pi} = 1; %h.perl.say; # OUTPUT: «(3.14159265358979e0=>1).MixHash»
(Any name that C<< => >> would convert to a string can also be used to build
a pair using "adverbial notation" and will appear that way when viewed
through C<.perl>, which is why we see C<:pi(1)> above.)
=end item1
Subscripts can be applied to any expression that returns a subscriptable
object, not just to variables:
say "__Hello__".match(/__(.*)__/)[0]; # OUTPUT: «「Hello」»
say "__Hello__".match(/__(.*)__/).[0]; # same, in method notation
Positional and associative subscripting are not mutually exclusive - for
example, L<Match> objects support both (each accessing a different set of
data). Also, to make list processing more convenient, class L<Any> provides a
fallback implementation for positional subscripts which simply treats the
invocant as a list of one element. (But there's no such fallback for
associative subscripts, so they throw a runtime error when applied to an
object that does not implement support for them.)
=begin code
say 42[0]; # OUTPUT: «42»
say 42<foo>; # ERROR: Type Int does not support associative indexing.
=end code
=head1 Nonexistent elements
What happens when a I<nonexistent> element is addressed by a subscript, is up
to the collection type in question. Standard L<Array> and L<Hash> collections
return the type object of their L<value type constraint|of> (which, by default,
is L<Any>) unless the collection has been declared with the
L<C<is default>|/type/Variable#trait_is_default> trait in which case the
returned value will be whatever the programmer declared it to be:
# no default values specified
my @array1; say @array1[10]; # OUTPUT: «(Any)»
my Int @array2; say @array2[10]; # OUTPUT: «(Int)»
my %hash1; say %hash1<foo>; # OUTPUT: «(Any)»
my Int %hash2; say %hash2<foo>; # OUTPUT: «(Int)»
# default values specified
my @array3 is default('--'); say @array3[10]; # OUTPUT: «--»
my Int @array4 is default(17); say @array4[10]; # OUTPUT: «17»
my %hash3 is default('Empty'); say %hash3<foo>; # OUTPUT: «Empty»
my Int %hash4 is default(4711); say %hash4<foo>; # OUTPUT: «4711»
However, other types of collections may react differently to subscripts that
address nonexistent elements:
say (0, 10, 20)[3]; # OUTPUT: «Nil»
say bag(<a a b b b>)<c>; # OUTPUT: «0»
say array[uint8].new(1, 2)[2] # OUTPUT: «0»
To silently skip nonexistent elements in a subscripting operation, see
L<#Truncating slices> and the L<#:v> adverb.
=head1 From the end
Positional indices are counted from the start of the collection, but there's
also a notation for addressing elements by their position relative to the end:
C<*-1> refers to the last element, C<*-2> to the second-to-last element, and so
on.
my @alphabet = 'A' .. 'Z';
say @alphabet[*-1]; # OUTPUT: «Z»
say @alphabet[*-2]; # OUTPUT: «Y»
say @alphabet[*-3]; # OUTPUT: «X»
B<Note>: The asterisk is important. Passing a bare negative integer (e.g.
C<@alphabet[-1]>) like you would do in many other programming languages, throws
an error in Perl 6.
What actually happens here, is that an expression like C<*-1> declares a code
object via L<Whatever>-currying - and the C<[ ]> subscript reacts to being
given a code object as an index, by calling it with the length of the
collection as argument and using the result value as the actual index. In other
words, C<@alphabet[*-1]> becomes C<@alphabet[@alphabet.elems - 1]>.
This means that you can use arbitrary expressions which depend on the size of
the collection:
=begin code :preamble<my @array; my $size;my $i;>
say @array[* div 2]; # select the middlemost element
say @array[$i % *]; # wrap around a given index ("modular arithmetic")
say @array[ -> $size { $i % $size } ]; # same as previous
=end code
=head1 Slices
When multiple elements of a collection need to be accessed, there's a shortcut
to doing multiple separate subscripting operations: Simply specify a I<list> of
indices/keys in the subscript, to get back a I<list> of elements - also called
a "slice" - in the same order.
For positional slices, you can mix normal indices with
L<from-the-end|#From the end> ones:
my @alphabet = 'a' .. 'z';
say @alphabet[15, 4, *-9, 11].perl; # OUTPUT: «("p", "e", "r", "l")»
In the C<*-number> construct above, C<*> indicates the end of the
array as explained above in the L<From the end|#From the end>
section. So if you want to take the last N elements of the array, you
will have to create a L<Range> that includes it.
(5802..5830).map( {.chr} )[*-10..*-5] # OUTPUT: «(ᚽ ᚾ ᚿ ᛀ ᛁ ᛂ)»
Using C<*> as the last element of the range will, effectively, return
the last elements of the collection.
For associative slices, the angle-brackets form often comes in handy:
my %color = kiwi => "green", banana => "yellow", cherry => "red";
say %color{"cherry", "kiwi"}; # OUTPUT: «(red green)»
say %color<cherry kiwi>; # OUTPUT: «(red green)»
say %color{*}; # OUTPUT: «(red yellow green)»
Be aware that slices are controlled by the I<type> of what is passed to
(L<one dimension of|#Multiple dimensions>) the subscript, not its length.
In particular the I<type> can be any of the following:
=item a lazy Iterable, that L<truncates|#Truncating slices> in [ ]
=item '*' (whatever-star), that returns the full slice (as if all keys/indices were specified)
=item any other object, that provides a single-element access rather than a slice
=item Callable, whatever is returned by the callable (this can lead to recursion)
=item empty, the full slice known as L<Zen slice|#Zen slices>
=item any iterable different from the above ones, normal slice
The notable difference between C<*> and Zen slice (empty) is that the L<Whatever> star
will cause full L<reification|/language/glossary#index-entry-Reify>, while Zen slice won't.
Both versions also L<de-cont|https://perl6advent.wordpress.com/2017/12/02/perl-6-sigils-variables-and-containers/#decont>.
So even a one-element list returns a slice, whereas a bare scalar value doesn't:
=begin code :skip-test
say @alphabet[2,]; # OUTPUT: «(c)»
say @alphabet[2,].^name; # OUTPUT: «List»
say @alphabet[2]; # OUTPUT: «c»
say @alphabet[2].^name; # OUTPUT: «Str»
=end code
(The angle-bracket form for associative subscripts works out because
L<word quoting|/language/quoting#Word_quoting:_qw> conveniently returns a
L<Str> in case of a single word, but a L<List> in case of multiple words.)
In fact, the list structure of (L<the current dimension of|#Multiple
dimensions>) the subscript is preserved across the slice operation
(but the kind of Iterable is not – the result is always just lists.)
=begin code :skip-test
say @alphabet[0, (1..2, (3,))]; # OUTPUT: «(a ((b c) (d)))»
say @alphabet[0, (1..2, [3,])]; # OUTPUT: «(a ((b c) (d)))»
say @alphabet[flat 0, (1..2, (3,))]; # OUTPUT: «(a b c d)»
say flat @alphabet[0, (1..2, (3,))]; # OUTPUT: «(a b c d)»
=end code
=head2 Truncating slices
Referring to nonexistent elements in a slice subscript causes the
output C<List> to contain undefined values (or L<whatever else|
#Nonexistent elements> the collection in question chooses to return for
nonexistent elements):
=begin code
my @letters = <a b c d e f>;
say @letters[3..7]; # OUTPUT: «(d e f (Any) (Any))»
=end code
This behavior, while at first glance may seem unintuitive, is desirable in
instances when you want to assign a value at an index in which a value does
not currently exist.
=begin code
my @letters;
say @letters; # OUTPUT: «[]»
@letters[^10] = 'a'..'z';
say @letters; # OUTPUT: «[a b c d e f g h i j]»
=end code
If you want the resulting slice to only include existing elements, you can
silently skip the non-existent elements using the L<#:v> adverb.
=begin code
my @letters = <a b c d e f>;
say @letters[3..7]:v; # OUTPUT: «(d e f)»
=end code
The behavior when indexing a collection via L<lazy|/language/list#Lazy_lists>
subscripts is different than when indexing with their eager counterparts.
When accessing via a lazy subscript, the resulting slice will be truncated.
=begin code :preamble<my @letters = <a b c d e f>;>
say @letters[lazy 3..7]; # OUTPUT: «(d e f)»
say @letters[ 3..*]; # OUTPUT: «(d e f)»
=end code
This behavior exists as a precaution to prevent runaway generation of massive,
potentially infinite C<Lists> and the out-of-memory issues that occur as a
result.
X<|Zen slices>
=head2 Zen slices
If you put the subscript operator behind an object without specifying any indices/keys at all, it simply
returns the subscripted object itself. Since it is empty but returns
everything, it is known as a I<Zen slice>.
Zen slicing is different from passing a Whatever-star (which, like a normal slice,
always returns a List of elements no matter the type of the original object)
or an empty list (which returns an empty slice):
my %bag := (orange => 1, apple => 3).Bag;
say %bag<>; # OUTPUT: «Bag(apple(3), orange)»
say %bag{}; # OUTPUT: «Bag(apple(3), orange)»
say %bag{*}; # OUTPUT: «(1 3)»
say %bag{()}; # OUTPUT: «()»
It is usually used to L<interpolate|/language/quoting#Interpolation:_qq>
entire arrays / hashes into strings:
my @words = "cruel", "world";
say "Hello, @words[]!" # OUTPUT: «Hello, cruel world!»
=head1 Multiple dimensions
Dimensions in subscripts are separated by a semicolon, allowing to mix lists of
elements and dimensions.
my @twodim = (<a b c>, (1, 2, 3));
say @twodim;
# OUTPUT: «[(a b c) (1 2 3)]»
say @twodim[0,1;1]; # 2nd element of both lists
# OUTPUT: «(b 2)»
Multidimensional subscripts can be used to flatten nested lists.
my @toomany = [[<a b>], [1, 2]];
say @toomany;
# OUTPUT: «[[a b] [1 2]]»
say @toomany[*;*];
# OUTPUT: «(a b 1 2)»
You can use L<Whatever|/type/Whatever> to select ranges or "rows" in
multidimensional subscripts.
my @a = [[1,2], [3,4]];
say @a[*;1]; # 2nd element of each sub list
# OUTPUT: «(2 4)»
my @a = (<1 c 6>, <2 a 4>, <5 b 3>);
say @a.sort( { $_[1] } ); # sort by 2nd column
# OUTPUT: «((2 a 4) (5 b 3) (1 c 6))»
=head1 Modifying elements
=comment TODO
=head1 Autovivification
Subscripts participate in "autovivification", i.e. the process by which arrays
and hashes automatically spring into existence when needed, so that you can
build nested data structures without having to pre-declare the collection type
at each level:
my $beatles;
$beatles{"White Album"}[0] = "Back in the U.S.S.R."; # autovivification!
say $beatles.perl; # OUTPUT: «${"White Album" => $["Back in the U.S.S.R."]}»
C<$beatles> started out undefined, but became a L<Hash> object because it was
subscripted with C<{ }> in the assignment. Similarly, C<$beatles{"White Album"}>
became an L<Array> object due to being subscripted with C<[ ]> in the
assignment.
Note that the subscripting itself does not cause autovivification: It only
happens when the result of the subscripting chain is I<assigned> to (or
otherwise mutated).
=comment TODO: Add expanded documentation on autovivification (which affects
more than just subscripts, i.e. also routines like C<push>), at
/language/datastructures.html, and link to it from here.
=head1 Binding
A subscripting expression may also be used as the left-hand-side of a binding
statement. If supported by the subscripted collection's type, this replaces
whatever value container would be naturally found at that "slot" of the
collection, with the specified container.
The built-in L<Array> and L<Hash> types support this in order to allow
building complex linked data structures:
my @a = 10, 11, 12, 13;
my $x = 1;
@a[2] := $x; # binding! (@a[2] and $x refer to the same container now.)
$x++; @a[2]++;
say @a; # OUTPUT: «[10 11 3 13]»
say $x; # OUTPUT: «3»
=comment TODO: Come up with a more practical/motivational example snippet.
=comment TODO: Add expanded documentation on building complex data structures
at /language/datastructures.html, and link to it from here.
See L<#method BIND-POS> and L<#method BIND-KEY> for the underlying mechanism.
=head1 Adverbs
The return value and possible side-effect of a subscripting operation can be
controlled using adverbs; these are defined on the relevant subscript
L<operators|/language/operators#Method_postfix_precedence>.
Beware of the relatively loose precedence of operator adverbs, which may
require you to add parentheses in compound expressions:
=for code :skip-test
if $foo || %hash<key>:exists { ... } # WRONG, tries to adverb the || op
=for code :preamble<my $foo; my %hash;>
if $foo || (%hash<key>:exists) { ... } # correct
if $foo or %hash<key>:exists { ... } # also correct
The supported adverbs are:
=head2 X<:exists|subscript adverb,:exists>
Return whether or not the requested element exists, instead of returning the
element's actual value. This can be used to distinguish between elements with
an undefined value, and elements that aren't part of the collection at all:
my @foo = Any, 10;
say @foo[0].defined; # OUTPUT: «False»
say @foo[0]:exists; # OUTPUT: «True»
say @foo[2]:exists; # OUTPUT: «False»
say @foo[0, 2]:exists; # OUTPUT: «(True False)»
my %fruit = apple => Any, orange => 10;
say %fruit<apple>.defined; # OUTPUT: «False»
say %fruit<apple>:exists; # OUTPUT: «True»
say %fruit<banana>:exists; # OUTPUT: «False»
say %fruit<apple banana>:exists; # OUTPUT: «(True False)»
May also be negated to test for non-existence:
=begin code :skip-test
say %fruit<apple banana>:!exists; # OUTPUT: «(False True)»
=end code
To check if I<all> elements of a slice exist, use an L<all> junction:
=begin code :preamble<my %fruit;>
if all %fruit<apple orange banana>:exists { ... }
=end code
C<:exists> can be combined with the L<#:delete> and L<#:p>/L<#:kv> adverbs -
in which case the behavior is determined by those adverbs, except that any
returned element I<value> is replaced with the corresponding L<Bool> indicating
element I<existence>.
See L<#method EXISTS-POS> and L<#method EXISTS-KEY> for the underlying
mechanism.
=head2 X<:delete|subscript adverb,:delete>
Delete the element from the collection or, if supported by the collection,
creates a hole at the given index, in addition to returning its value.
my @tens = 0, 10, 20, 30;
say @tens[3]:delete; # OUTPUT: «30»
say @tens; # OUTPUT: «[0 10 20]»
my %fruit = apple => 5, orange => 10, banana => 4, peach => 17;
say %fruit<apple>:delete; # OUTPUT: «5»
say %fruit<peach orange>:delete; # OUTPUT: «(17 10)»
say %fruit; # OUTPUT: «{banana => 4}»
Note that assigning C<Nil> will revert the container at the given index to its
default value. It will not create a hole. The created holes can be tested for
with C<:exists> but iteration will not skip them and produce undefined values
instead.
my @a = 1, 2, 3;
@a[1]:delete;
say @a[1]:exists;
# OUTPUT: «False»
.say for @a;
# OUTPUT: «1(Any)3»
With the negated form of the adverb, the element is not actually deleted. This
means you can pass a flag to make it conditional:
=begin code :skip-test
say %fruit<apple> :delete($flag); # deletes the element only if $flag is
# true, but always returns the value.
=end code
Can be combined with the L<#:exists> and L<#:p>/L<#:kv>/L<#:k>/L<#:v> adverbs -
in which case the return value will be determined by those adverbs, but the
element will at the same time also be deleted.
See L<#method DELETE-POS> and L<#method DELETE-KEY> for the underlying
mechanism.
=head2 X<:p|subscript adverb,:p>
Return both the index/key and the value of the element, in the form of a
L<Pair>, and silently skip nonexistent elements:
my @tens = 0, 10, 20, 30;
say @tens[1]:p; # OUTPUT: «1 => 10»
say @tens[0, 4, 2]:p; # OUTPUT: «(0 => 0 2 => 20)»
my %month = Jan => 1, Feb => 2, Mar => 3;
say %month<Feb>:p; # OUTPUT: «Feb => 2»
say %month<Jan Foo Mar>:p; # OUTPUT: «(Jan => 1 Mar => 3)»
If you I<don't> want to skip nonexistent elements, use the negated form:
=begin code :skip-test
say %month<Jan Foo Mar>:!p; # OUTPUT: «(Jan => 1 Foo => (Any) Mar => 3)»
=end code
Can be combined with the L<#:exists> and L<#:delete> adverbs.
See also the L<pairs> routine.
=head2 X<:kv|subscript adverb,:kv>
Return both the index/key and the value of the element, in the form of a
L<List>, and silently skip nonexistent elements. When used on a
L<slice|#Slices>, the return value is a single flat list of interleaved keys
and values:
my @tens = 0, 10, 20, 30;
say @tens[1]:kv; # OUTPUT: «(1 10)»
say @tens[0, 4, 2]:kv; # OUTPUT: «(0 0 2 20)»
my %month = Jan => 1, Feb => 2, Mar => 3;
say %month<Feb>:kv; # OUTPUT: «(Feb 2)»
say %month<Jan Foo Mar>:kv; # OUTPUT: «(Jan 1 Mar 3)»
If you I<don't> want to skip nonexistent elements, use the negated form:
=begin code :skip-test
say %month<Jan Foo Mar>:!kv; # OUTPUT: «(Jan 1 Foo (Any) Mar 3)»
=end code
This adverb is commonly used to iterate over slices:
=begin code :preamble<my %month>
for %month<Feb Mar>:kv -> $month, $i {
say "$month had {Date.new(2015, $i, 1).days-in-month} days in 2015"
}
=end code
Can be combined with the L<#:exists> and L<#:delete> adverbs.
See also the L<kv> routine.
=head2 X<:k|subscript adverb,:k>
Return only the index/key of the element, rather than its value, and silently
skip nonexistent elements:
my @tens = 0, 10, 20, 30;
say @tens[1]:k; # OUTPUT: «1»
say @tens[0, 4, 2]:k; # OUTPUT: «(0 2)»
my %month = Jan => 1, Feb => 2, Mar => 3;
say %month<Feb>:k; # OUTPUT: «Feb»
say %month<Jan Foo Mar>:k; # OUTPUT: «(Jan Mar)»
If you I<don't> want to skip nonexistent elements, use the negated form:
=begin code :skip-test
say %month<Jan Foo Mar>:!k; # OUTPUT: «(Jan Foo Mar)»
=end code
See also the L<keys> routine.
=head2 X<:v|subscript adverb,:v>
Return the bare value of the element (rather than potentially returning a
mutable value container), and silently skip nonexistent elements:
=begin code
my @tens = 0, 10, 20, 30;
say @tens[1]:v; # OUTPUT: «10»
say @tens[0, 4, 2]:v; # OUTPUT: «(0, 20)»
@tens[3] = 31; # OK
@tens[3]:v = 31; # ERROR, Cannot modify an immutable Int (31)
my %month = Jan => 1, Feb => 2, Mar => 3;
say %month<Feb>:v; # OUTPUT: «2»
say %month<Jan Foo Mar>:v; # OUTPUT: «(1 3)»
=end code
If you I<don't> want to skip nonexistent elements, use the negated form:
=begin code :skip-test
say %month<Jan Foo Mar>:!v; # OUTPUT: «(1 (Any) 3)»
=end code
See also the L<values> routine.
=head1 Custom types
The subscripting interfaces described on this page are not meant to be
exclusive to Perl 6's built-in collection types - you can (and should)
reuse them for any custom type that wants to provide access to data by
index or key.
You don't have to manually overload the L<C<postcircumfix [ ]>|
/routine/[ ]#postcircumfix_[_]> and L<C<postcircumfix { }>|
/routine/{ }#postcircumfix_{_}> operators and re-implement all their magic,
to achieve that - instead, you can rely on the fact that their standard
implementation dispatches to a well-defined set of low-level methods behind
the scenes. For example:
=table
when you write: this gets called behind the scenes:
=============== ==============================================
%foo<aa> %foo.AT-KEY("aa")
%foo<aa>:delete %foo.DELETE-KEY("aa")
@foo[3, 4, 5] @foo.AT-POS(3), @foo.AT-POS(4), @foo.AT-POS(5)
@foo[*-1] @foo.AT-POS(@foo.elems - 1)
So in order to make subscripting work, you only have to implement or
delegate those low-level methods (L<detailed below
|#Methods_to_implement_for_positional_subscripting>) for your custom type.
If you do, you should also let your type compose the L<C<Positional>|
/type/Positional> or L<C<Associative>|/type/Associative> role,
respectively. This doesn't add any functionality per se, but announces (and
may be used to check) that the type implements the corresponding
subscripting interface.
=head2 Custom type example
=comment TODO: Maybe factor this out into a tutorial page
Imagine a HTTP::Header type which, despite being a custom class with special
behavior, can be indexed like a hash:
=begin code
my $request = HTTP::Request.new(GET => "perl6.org");
say $request.header.^name; # OUTPUT: «HTTP::Header»
$request.header<Accept> = "text/plain";
$request.header{'Accept-' X~ <Charset Encoding Language>} = <utf-8 gzip en>;
$request.header.push('Accept-Language' => "fr"); # like .push on a Hash
say $request.header<Accept-Language>.perl; # OUTPUT: «["en", "fr"]»
my $rawheader = $request.header.Str; # stringify according to HTTP spec
=end code
The simplest way to implement this class, would be to give it an attribute of
type L<Hash>, and delegate all subscripting and iterating related functionality
to that attribute (using a custom type constraint to make sure users don't
insert anything invalid into it):
=begin code :skip-test
class HTTP::Header does Associative {
subset StrOrArrayOfStr where Str | ( Array & {.all ~~ Str} );
has %!fields of StrOrArrayOfStr
handles <AT-KEY EXISTS-KEY DELETE-KEY push
iterator list kv keys values>;
method Str { #`[not shown, for brevity] }
}
=end code
However, HTTP header field names are supposed to be case-insensitive (and
preferred in camel-case). We can accommodate this by taking the C<*-KEY>
and C<push> methods out of the C<handles> list, and implementing them
separately like this:
=begin code :skip-test
method AT-KEY ($key) is rw { %!fields{normalize-key $key} }
method EXISTS-KEY ($key) { %!fields{normalize-key $key}:exists }
method DELETE-KEY ($key) { %!fields{normalize-key $key}:delete }
method push(*@_) { #`[not shown, for brevity] }
sub normalize-key ($key) { $key.subst(/\w+/, *.tc, :g) }
=end code
Note that subscripting C<%!fields> returns an appropriate rw container, which
our C<AT-KEY> can simply pass on.
However, we may prefer to be less strict about user input and instead take
care of sanitizing the field values ourselves. In that case, we can remove
the C<StrOrArrayOfStr> type constraint on C<%!fields>, and replace our
C<AT-KEY> implementation with one that returns a custom C<Proxy> container
which takes care of sanitizing values on assignment:
=begin code :skip-test
multi method AT-KEY (::?CLASS:D: $key) is rw {
my $element := %!fields{normalize-key $key};
Proxy.new(
FETCH => method () { $element },
STORE => method ($value) {
$element = do given $value».split(/',' \s+/).flat {
when 1 { .[0] } # a single value is stored as a string
default { .Array } # multiple values are stored as an array
}
}
);
}
=end code
Note that declaring the method as C<multi> and restricting it to C<:D> (defined
invocants) makes sure that the undefined case is passed through to the default
implementation provided by C<Any> (which is involved in auto-vivification).
=head2 Methods to implement for positional subscripting
In order to make index-based subscripting via L<C<postcircumfix [ ]>|
/routine/[ ]#postcircumfix_[_]> work for your custom type, you should
implement at least C<elems>, C<AT-POS> and C<EXISTS-POS> - and optionally
others as detailed below.
=head3 method elems
multi method elems(::?CLASS:D:)
Expected to return a number indicating how many subscriptable elements
there are in the object. May be called by users directly, and is also
called by L<C<postcircumfix [ ]>|/routine/[ ]#postcircumfix_[_]> when
indexing elements from the end, as in C<@foo[*-1]>.
If not implemented, your type will inherit the default implementation from
C<Any> that always returns C<1> for defined invocants - which is most
likely not what you want. So if the number of elements cannot be known for
your positional type, add an implementation that L<fail>s or L<die>s, to
avoid silently doing the wrong thing.
=head3 method AT-POS
=comment When modifying this section, please also adapt the AT-KEY
section accordingly as they are very similar.
multi method AT-POS (::?CLASS:D: $index)
=comment TODO: Cover the case of multi-dim indices (also for all the other
methods below), after jnthn's ongoing refactor is finished.
Expected to return the element at position C<$index>. This is what
L<C<postcircumfix [ ]>|/routine/[ ]#postcircumfix_[_]> normally calls.
If you want an element to be mutable (like they are for the built-in
L<Array> type), you'll have to make sure to return it in the form of an
item container that evaluates to the element's value when read, and updates
it when assigned to. (Remember to use C<return-rw> or the C<is rw> routine
trait to make that work; see the L<example
|/language/subscripts#Custom_type_example>.)
=head3 method EXISTS-POS
=comment When modifying this section, please also adapt the EXISTS-KEY
section accordingly as they are very similar.
multi method EXISTS-POS (::?CLASS:D: $index)
Expected to return a Bool indicating whether or not there is an element at
position C<$index>. This is what L<C<postcircumfix [ ]>|
/routine/[ ]#postcircumfix_[_]> calls when invoked like C<@foo[42]:exists>.
What "existence" of an element means, is up to your type.
If you don't implement this, your type will inherit the default
implementation from C<Any>, which returns True for 0 and False for any
other index - which is probably not what you want. So if checking for
element existence cannot be done for your type, add an implementation that
L<fail>s or L<die>s, to avoid silently doing the wrong thing.
=head3 method DELETE-POS
=comment When modifying this section, please also adapt the DELETE-KEY
section accordingly as they are very similar.
multi method DELETE-POS (::?CLASS:D: $index)
Expected to delete the element at position C<$index>, and return the value
it had. This is what L<C<postcircumfix [ ]>|/routine/[ ]#postcircumfix_[_]>
calls when invoked like C<@foo[42]:delete>.
What "deleting" an element means, is up to your type.
Implementing this method is optional; if you don't, users trying to delete
elements from an object of this type will get an appropriate error message.
=head3 method ASSIGN-POS
=comment When modifying this section, please also adapt the ASSIGN-KEY
section accordingly as they are very similar.
multi method ASSIGN-POS (::?CLASS:D: $index, $new)
Expected to set the element at position C<$index> to the value C<$new>.
Implementing this is entirely optional; if you don't, C<self.AT-POS($index)
= $new> is used instead, and if you do, you should make sure it has the
same effect.
This is meant as an opt-in performance optimization, so that simple
assignments like C<@numbers[5] = "five"> can operate without having to call
C<AT-POS> (which would have to create and return a potentially expensive
container object).
Note that implementing C<ASSIGN-POS> does I<not> relieve you from making
C<AT-POS> an C<rw> method though, because less trivial
assignments/modifications such as C<@numbers[5]++> will still use
C<AT-POS>.
=head3 method BIND-POS
=comment When modifying this section, please also adapt the BIND-KEY
section accordingly as they are very similar.
multi method BIND-POS (::?CLASS:D: $index, \new)
Expected to bind the value or container C<new> to the slot at position
C<$index>, replacing any container that would be naturally found there.
This is what is called when you write:
=begin code :preamble<my @numbers;>
my $x = 10;
@numbers[5] := $x;
=end code
The generic L<Array> class supports this in order to allow building complex
linked data structures, but for more domain-specific types it may not make
sense, so don't feel compelled to implement it. If you don't, users will
get an appropriate error message when they try to bind to a positional slot
of an object of this type.
=head2 method STORE
=comment When modifying this section, please also adapt the STORE
section in Associative accordingly as they are very similar.
method STORE (::?CLASS:D: \values, :$initialize)
This method should only be supplied if you want to support the:
=for code :preamble<role Foo {}>
my @a is Foo = 1,2,3;
syntax for binding your implementation of the C<Positional> role.
Should accept the values to (re-)initialize the object with. The optional
named parameter will contain a C<True> value when the method is called on
the object for the first time. Should return the invocant.
=head2 Methods to implement for associative subscripting
In order to make key-based subscripting via L<C<postcircumfix { }>|
/routine/{ }#postcircumfix_{_}> work for your custom type, you should
implement at least C<AT-KEY> and C<EXISTS-KEY> - and optionally
others as detailed below.
=head3 method AT-KEY
=comment When modifying this section, please also adapt the AT-POS
section accordingly as they are very similar.
multi method AT-KEY (::?CLASS:D: $key)
Expected to return the element associated with C<$key>. This is what
L<C<postcircumfix { }>|/routine/{ }#postcircumfix_{_}> normally calls.
If you want an element to be mutable (like they are for the built-in
L<Hash> type), you'll have to make sure to return it in the form of an item
container that evaluates to the element's value when read, and updates it
when assigned to. (Remember to use C<return-rw> or the C<is rw> routine
trait to make that work; see the L<example
|/language/subscripts#Custom_type_example>.)
On the other hand if you want your collection to be read-only, feel free
to return non-container values directly.
=head3 method EXISTS-KEY
=comment When modifying this section, please also adapt the EXISTS-POS
section accordingly as they are very similar.
multi method EXISTS-KEY (::?CLASS:D: $key)
Expected to return a Bool indicating whether or not there is an element
associated with C<$key>. This is what L<C<postcircumfix { }>
|/routine/{ }#postcircumfix_{_}> calls when invoked like
C<< %foo<aa>:exists >>.
What "existence" of an element means, is up to your type.
If you don't implement this, your type will inherit the default
implementation from C<Any>, which always returns False - which is probably
not what you want. So if checking for element existence cannot be done for
your type, add an implementation that L<fail>s or L<die>s, to avoid
silently doing the wrong thing.
=head3 method DELETE-KEY
=comment When modifying this section, please also adapt the DELETE-POS
section accordingly as they are very similar.
multi method DELETE-KEY (::?CLASS:D: $key)
Expected to delete the element associated with C<$key>, and return the
value it had. This is what L<C<postcircumfix { }>
|/routine/{ }#postcircumfix_{_}> calls when invoked like
C<< %foo<aa>:delete >>.
What "deleting" an element means, is up to your type - though it should
usually cause C<EXISTS-KEY> to become C<False> for that key.
Implementing this method is optional; if you don't, users trying to delete
elements from an object of this type will get an appropriate error message.
=head3 method ASSIGN-KEY
=comment When modifying this section, please also adapt the ASSIGN-POS
section accordingly as they are very similar.
multi method ASSIGN-KEY (::?CLASS:D: $key, $new)
Expected to set the element associated with C<$key> to the value C<$new>.
Implementing this is entirely optional; if you don't, C<self.AT-KEY($key) =
$new> is used instead, and if you do, you should make sure it has the same
effect.
This is meant as an opt-in performance optimization, so that simple
assignments C<< %age<Claire> = 29 >> can operate without having to call
C<AT-KEY> (which would have to create and return a potentially expensive
container object).
Note that implementing C<ASSIGN-KEY> does I<not> relieve you from making
C<AT-KEY> an C<rw> method though, because less trivial
assignments/modifications such as C<< %age<Claire>++ >> will still use
C<AT-KEY>.
=head3 method BIND-KEY
=comment When modifying this section, please also adapt the BIND-POS
section accordingly as they are very similar.
multi method BIND-KEY (::?CLASS:D: $key, \new)
Expected to bind the value or container C<new> to the slot associated with
C<$key>, replacing any container that would be naturally found there.
This is what is called when you write:
=begin code :preamble<my %age;>
my $x = 10;
%age<Claire> := $x;
=end code
The generic L<Hash> class supports this in order to allow building complex
linked data structures, but for more domain-specific types it may not make
sense, so don't feel compelled to implement it. If you don't, users will
get an appropriate error message when they try to bind to an associative
slot of an object of this type.
=head3 method STORE
=comment When modifying this section, please also adapt the STORE
section in Positional accordingly as they are very similar.
method STORE (::?CLASS:D: \values, :$initialize)
This method should only be supplied if you want to support the:
=for code :preamble<role Foo {}>
my %h is Foo = a => 42, b => 666;
syntax for binding your implementation of the C<Associative> role.
Should accept the values to (re-)initialize the object with, which either
could consist of C<Pair>s, or separate key/value pairs. The optional
named parameter will contain a C<True> value when the method is called on
the object for the first time. Should return the invocant.
=end pod
# vim: expandtab softtabstop=4 shiftwidth=4 ft=perl6