@@ -19,4 +19,74 @@ include L<Parcel>, L<List>, L<Array>, L<Range>, and L<Buf>.
19
19
Returns the type constraint for elements of the positional container. Defaults
20
20
to L < Mu > .
21
21
22
+ = head2 sub postcircumfix:<[ ]>
23
+
24
+ sub postcircumfix:<[ ]>(@container, *@index, :$k, :$v, :$kv, :$p, :$exists, :$delete)
25
+
26
+ Universal interface for positional access to zero or more elements of the
27
+ C < @container > . Elements can be accessed by zero-based
28
+ L < integers|/type/Int > , or by C < callable objects|/type/Callable > , which will be
29
+ passed the number of elements in the container, making indexing from the end
30
+ esay:
31
+
32
+ my @a = <a b c>;
33
+ say @a[0]; # a
34
+ say @a[*-1]; # c
35
+ say @a[ sub $x { $x - 1 }]; # c
36
+
37
+ If more than one index is given, a list of elements is returned:
38
+
39
+ my @a = <a b c>;
40
+ say @a[0, 2]; # a c
41
+
42
+ Different access mode (integers vs. callables) can be mixed inside a single
43
+ positional access:
44
+
45
+ my @a = <a b c>;
46
+ say @a[*-1, 0]; # c a
47
+
48
+ Each access of a single element goes through a method called C < AT-POS > , which
49
+ derivative types can override.
50
+
51
+ Accesses with positive integers beyond the end of the container are allowed
52
+ for mutable data structures (such as L < Array > ), and return a L < Scalar >
53
+ container that, on assignment, autovivifies the accessed array element:
54
+
55
+ my @a = <a b>;
56
+ @a[2] = 'c';
57
+ say @a; # a b c
58
+
59
+ Where detected at compile time, assignment to a positional index can be
60
+ short-circuted through a method called C < ASSIGN-POS > .
61
+
62
+ The adverb C < :delete > deletes the specified indexes, and returns the deleted
63
+ values:
64
+
65
+ my @a = <a b c>;
66
+ say @a[2]:delete; # c
67
+ say @a; # a b
68
+
69
+ Deletion of elements is impelemented in the C < DELETE-POS > method, which
70
+ derivative types can override.
71
+
72
+ The adverb C < :exists > make the positional accesses return a L < Bool > for each
73
+ index, indicating whether the container has a value at the index:
74
+
75
+ my @a = 1, Any;
76
+
77
+ say @a[0, 1, 2]:exists; # True True False
78
+
79
+ The adverbs C < :k > (for I < key > ), C < :v > (for I < value > ), C < :kv > (for
80
+ I < key/value > ) and C < :p > (for L < Pair|/type/Pair > ) are mutually exclusive, and
81
+ control the format of the return value. C < :k > only returns the key (which is
82
+ always the index on Positional types), C < :v > only the value (the default),
83
+ C < :kv > a L < Parcel > of key and value, and C < :p > a L < Pair|/type/Pair > with the
84
+ key being the index, and the value being the value stored in the container
85
+
86
+ for <a b c>.kv -> $k, $v {
87
+ say "$k: $v"; # 0: a
88
+ # 1: b
89
+ # 2: c
90
+ }
91
+
22
92
= end pod
0 commit comments