-
Notifications
You must be signed in to change notification settings - Fork 292
/
Hash.pod6
507 lines (372 loc) · 18 KB
/
Hash.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
=begin pod :kind("Type") :subkind("class") :category("composite")
=TITLE class Hash
=SUBTITLE Mapping from strings to itemized values
class Hash is Map { }
A C<Hash> is a mutable L<Map|/type/Map>; it implements C<Associative> through
its inheritance of C<Map> and as such provides support for looking up values
using keys, providing support for L<associative
subscripting|/language/subscripts#Methods_to_implement_for_associative_subscripting>.
Although the order of the hashes is guaranteed to be random in every single
call, still successive calls to C<.keys> and C<.values> are guaranteed to return
them in the same order:
my %orig = :1a, :2b; my %new = :5b, :6c;
%orig{ %new.keys } = %new.values;
say %orig.perl; # OUTPUT: «{:a(1), :b(5), :c(6)}»
In this case, C<b> will always be associated to 5 and C<c> to 6; even if two
successive calls to C<keys> will return them in different order. Successive
calls to any of them separately and repeatedly will always return the same order
in any program invocation.
Please see the section on L<hash literals|/language/syntax#Hash_literals> for
different ways to declare a hash. Additionally, they can be declared using curly
braces as long as these rules are followed:
=item Empty curly braces will always declare an empty hash.
=item A reference to $_ (even implicit) will instead declare a block.
=item A C<Pair> or variable with C<%> as the first element will declare a hash.
=for code
given 3 { say WHAT {3 => 4, :b} }; # OUTPUT: «(Hash)»
given 3 { say WHAT {3 => 4, :b($_)} }; # OUTPUT: «(Block)»
given 3 { say WHAT {3 => 4, :b(.Num)} };# OUTPUT: «(Block)»
say { 'a',:b(3), 'c' }.^name; # OUTPUT: «Block»
The next-to-last two cases are examples of the generation of C<Block>s in the
presence of the topic variable C<$_>. The last case does not meet the third
criterium for generating a hash, and thus generates a C<Block>.
A % in front of parentheses or square brackets will generate a Hash as long as
the elements can be paired.
say %( 'a', 3, :b(3), 'c', 3 ).^name; # OUTPUT: «Hash»
Elements in this hash can be paired both sides of the Pair C<:b(3)>.
say %(«a b c 1 2 3»).^name; # OUTPUT: «Hash»
An empty hash can be initialized either with empty curly braces or, since 6.d, C<%()>.
say %().^name; # OUTPUT: «Hash»
say {}.^name; # OUTPUT: «Hash»
=head1 Methods
=head2 method classify-list
Defined as:
multi method classify-list(&mapper, *@list, :&as --> Hash:D)
multi method classify-list(%mapper, *@list, :&as --> Hash:D)
multi method classify-list(@mapper, *@list, :&as --> Hash:D)
Populates a L«C<Hash>|/type/Hash» by classifying the possibly-empty C<@list> of
values using the given C<mapper>, optionally altering the values using the
C<:&as> L«C<Callable>|/type/Callable». The C<@list> cannot be lazy.
The mapper can be a L«C<Callable>|/type/Callable» that takes a single argument,
an L«C<Associative>|/type/Associative», or an L«C<Iterable>|/type/Iterable»;
this C<Callable> is guaranteed to be called only once per item.
With L«C<Associative>|/type/Associative» and an L«C<Iterable>|/type/Iterable»
mappers, the values in the C<@list> represent the key and index of the mapper's
value respectively. A L«C<Callable>|/type/Callable» mapper will be executed
once per each item in the C<@list>, with that item as the argument and its
return value will be used as the mapper's value.
=head3 Simple classification
In simple classification mode, each mapper's value is any non-C<Iterable> and
represents a key to classify C<@list>'s item under:
=begin code
say % .classify-list: { $_ %% 2 ?? 'even' !! 'odd' }, ^10;
# OUTPUT: «{even => [0 2 4 6 8], odd => [1 3 5 7 9]}»
my @mapper = <zero one two three four five>;
my %hash = foo => 'bar';
say %hash.classify-list: @mapper, 1, 2, 3, 4, 4;
# OUTPUT: «{foo => bar, four => [4 4], one => [1], three => [3], two => [2]}»
=end code
The mapper's value is used as the key of the L«C<Hash>|/type/Hash» to
which the C<@list>'s item will be L«C<push>ed|/routine/push». See
L«C<.categorize-list>|/routine/categorize-list» if you wish to classify an item
into multiple categories at once.
=head3 Multi-level classification
In multi-level classification mode, each mapper's value is an
L«C<Iterable>|/type/Iterable» that represents a tree of hash keys to classify
C<@list>'s item under:
say % .classify-list: {
[
(.is-prime ?? 'prime' !! 'non-prime'),
($_ %% 2 ?? 'even' !! 'odd' ),
]
}, ^10;
# OUTPUT:
# {
# non-prime => {
# even => [0 4 6 8],
# odd => [1 9]
# },
# prime => {
# even => [2],
# odd => [3 5 7]
# }
# }
In the case we are using C<Iterables> and not C<Callables>, each of those
L«C<Iterable>|/type/Iterable»s must
have the same number
of elements, or the method will throw an exception. This restriction exists to
avoid conflicts when the same key is a leaf of one value's classification but a
node of another value's classification.
=for code
my @mapper = [['1a','1b','1c'],['2a','2b','2c'],['3a','3b','3c']];
say % .classify-list: @mapper, 1,2,1,1,2,0;
# OUTPUT: «{1a => {1b => {1c => [0]}}, 2a => {2b => {2c => [1 1 1]}}, 3a => {3b => {3c => [2 2]}}}»
Every element of the array represents a different level in the tree, with the
elements of the list that is being mapped used as index, and the elements of
the mapper array used as keys to the different levels. So C<0> selects the
first sub-array and then the subsequent levels are built by running over the
rest of the elements of that sub-array.
=for code
my @mapper = [['1a','1b'],['2a','2b'],['3a','3b']];
say % .classify-list: @mapper, 1,0,1,1,1,0,2;
# OUTPUT: «{1a => {1b => [0 0]}, 2a => {2b => [1 1 1 1]}, 3a => {3b => [2]}}»
From version 6.d, trying to use C<Iterable>s of different size will throw an
error:
=for code :skip-test<Illustrates error>
my @mapper = [<1a 1b>, <2a 2b 2fail>];
say % .classify-list: @mapper, 1,0,1,1,1,0;
# OUTPUT: «mapper on classify-list computed to an item with different number
# of elements in it than previous items, which cannot be used because all
# values need to have the same number of elements. Mixed-level classification
# is not supported. in block <unit>…»
=head3 C<:&as> value modifier
If C<:&as> L«C<Callable>|/type/Callable» argument is specified, it will be
called once per each item of C<@list>, with the value as the argument, and
its return value will be used instead of the original C<@list>'s item:
say % .classify-list: :as{"Value is $_"}, { $_ %% 2 ?? 'even' !! 'odd' }, ^5;
# OUTPUT (slightly altered manually, for clarity):
# {
# even => ['Value is 0', 'Value is 2', 'Value is 4'],
# odd => ['Value is 1', 'Value is 3']
# }
=head2 method categorize-list
Defined as:
multi method categorize-list(&mapper, *@list, :&as --> Hash:D)
multi method categorize-list(%mapper, *@list, :&as --> Hash:D)
multi method categorize-list(@mapper, *@list, :&as --> Hash:D)
Populates a L«C<Hash>|/type/Hash» by classifying the
possibly-empty C<@list> of values using the given C<mapper>, optionally
altering the values using the C<:&as> L«C<Callable>|/type/Callable». The
C<@list> cannot be lazy.
The mapper can be a L«C<Callable>|/type/Callable» that takes a single argument,
an L«C<Associative>|/type/Associative», or an L«C<Iterable>|/type/Iterable».
With L«C<Associative>|/type/Associative» and an L«C<Iterable>|/type/Iterable»
mappers, the values in the C<@list> represent the key and index of the mapper's
value respectively. A L«C<Callable>|/type/Callable» mapper will be executed
once per each item in the C<@list>, with that item as the argument and its
return value will be used as the mapper's value.
=head3 Simple categorization
The mapper's value is expected to be a possibly empty list of
non-L«C<Iterables>|/type/Iterable» that represent categories to place the value
into:
say % .categorize-list: {
gather {
take 'prime' if .is-prime;
take 'largish' if $_ > 5;
take $_ %% 2 ?? 'even' !! 'odd';
}
}, ^10;
# OUTPUT:
# {
# prime => [2 3 5 7]
# even => [0 2 4 6 8],
# odd => [1 3 5 7 9],
# largish => [6 7 8 9],
# }
Notice how some items, e.g. C<6> and C<7>, are present in several categories.
=head3 Multi-level categorization
In multi-level categorization, the categories produced by the mapper are
L<Iterables|/type/Iterable> and categorization combines features
of L<classify|/routine/classify>, by producing nested hashes of classifications
for each category.
say % .categorize-list: {
[
$_ > 5 ?? 'largish' !! 'smallish',
.is-prime ?? 'prime' !! 'non-prime',
],
}, ^10;
# OUTPUT:
# {
# largish => {
# non-prime => [6 8 9],
# prime => [7]
# },
# smallish => {
# non-prime => [0 1 4],
# prime => [2 3 5]
# }
# }
The mapper in the snippet above produces a single-item list (note the
significant
trailing comma) with a two-item C<Array> in it. The first item in that array
indicates the first level of classification: the C<largish>/C<smallish>
categories the routine produces. The second item in that array indicates
further levels of classification, in our case the classification into
C<prime>/C<non-prime> inside of each category.
B<NOTE:>: every L«C<Iterables>|/type/Iterable» category
must have the same number of elements, or the method will throw an exception.
This restriction exists to avoid conflicts when the same key is a
leaf of one value's classification but a node of another value's classification.
=head3 C<:&as> value modifier
If C<:&as> L«C<Callable>|/type/Callable» argument is specified, it will be
called once per each item of C<@list>, with the value as the argument, and
its return value will be used instead of the original C<@list>'s item:
say % .categorize-list: :as{"Value is $_"}, { $_ %% 2 ?? 'even' !! 'odd' }, ^5;
# OUTPUT (slightly altered manually, for clarity):
# {
# even => ['Value is 0', 'Value is 2', 'Value is 4'],
# odd => ['Value is 1', 'Value is 3']
# }
=head2 method push
Defined as:
multi method push(Hash:D: *@new)
Adds the C<@new> elements to the hash with the same semantics as hash
assignment, but with three exceptions:
=item The hash isn't emptied first, i.e. old pairs are not deleted.
=item If a key already exists in the hash, and the corresponding value is an
L<Array|/type/Array>, the new value is pushed onto the array (instead of replacing it).
=item If a key already exists in the hash, and the corresponding value is not
an L<Array|/type/Array>, old and new value are both placed into an array in the place
of the old value.
Example:
my %h = a => 1;
%h.push: (a => 1); # a => [1,1]
%h.push: (a => 1) xx 3 ; # a => [1,1,1,1,1]
%h.push: (b => 3); # a => [1,1,1,1,1], b => 3
%h.push('c' => 4); # a => [1,1,1,1,1], b => 3, c => 4
push %h, 'd' => 5; # a => [1,1,1,1,1], b => 3, c => 4, d => 5
Please note that C<Pair>s or
L<colon pairs|/language/glossary#index-entry-Colon_Pair> as arguments to push
will be treated as extra named arguments and as such wont end up the C<Hash>.
The same applies to the sub C<push>.
my %h .= push(e => 6);
push %h, f => 7;
say %h.perl;
# OUTPUT: «{}»
Also note that push can be used as a replacement for assignment during hash
initialization very useful ways. Take for instance the case of an inverted
index:
my %wc = 'hash' => 323, 'pair' => 322, 'pipe' => 323;
(my %inv).push: %wc.invert;
say %inv; # OUTPUT: «{322 => pair, 323 => [pipe hash]}»
Note that such an initialization could also be written as
my %wc = 'hash' => 323, 'pair' => 322, 'pipe' => 323;
my %inv .= push: %wc.invert;
B<Note:> Compared to L«C<append>|/routine/append», C<push> will add the given
value as is, whereas C<append> will L«C<slip>|/routine/slip» it in:
my %ha = :a[42, ]; %ha.push: "a" => <a b c a>;
say %ha; # OUTPUT: «{a => [42 (a b c a)]}»
my %hb = :a[42, ]; %hb.append: "a" => <a b c a>;
say %hb; # OUTPUT: «{a => [42 a b c a]}»
=head2 method append
Defined as:
method append(+@values)
Append the provided Pairs or even sized list to the Hash. If a key already
exists, turn the existing value into an L<Array|/type/Array> and push new value
onto that C<Array>. Please note that you can't mix even sized lists and lists
of Pairs. Also, bare C<Pair>s or colon pairs will be treated as L<named
arguments|/type/Signature#Positional_vs._Named> to C<.append>.
my %h = a => 1;
%h.append('b', 2, 'c', 3);
%h.append( %(d => 4) );
say %h;
# OUTPUT: «{a => 1, b => 2, c => 3, d => 4}»
%h.append('a', 2);
# OUTPUT: «{{a => [1 2], b => 2, c => 3, d => 4}»
B<Note:> Compared to L«C<push>|/routine/push», C<append> will
L«C<slip>|/routine/slip» in the given value, whereas C<push> will add it as
is:
my %hb = :a[42, ]; %hb.append: "a" => <a b c a>;
say %hb; # OUTPUT: «{a => [42 a b c a]}»
my %ha = :a[42, ]; %ha.push: "a" => <a b c a>;
say %ha; # OUTPUT: «{a => [42 (a b c a)]}»
=head2 method default
Defined as:
method default()
Returns the default value of the invocant, i.e. the value which is returned when
a non existing key is used to access an element in the C<Hash>. Unless the
C<Hash> is declared as having a default value by using the
L<is default|/syntax/trait is default> trait the method returns the type object
C<(Any)>.
my %h1 = 'apples' => 3, 'oranges' => 7;
say %h1.default; # OUTPUT: «(Any)»
say %h1{'bananas'}; # OUTPUT: «(Any)»
my %h2 is default(1) = 'apples' => 3, 'oranges' => 7;
say %h2.default; # OUTPUT: «1»
say %h2{'apples'} + %h2{'bananas'}; # OUTPUT: «4»
=head2 method keyof
Defined as:
method keyof()
Returns the type constraint for the keys of the invocant. For
normal hashes the method returns the coercion type C<(Str(Any))>
while for L<non-string keys|/type/Hash#Non-string_keys>
hashes the type used in the declaration of the C<Hash> is returned.
my %h1 = 'apples' => 3, 'oranges' => 7; # (no key type specified)
say %h1.keyof; # OUTPUT: «(Str(Any))»
my %h2{Str} = 'oranges' => 7; # (keys must be of type Str)
say %h2.keyof; # (Str)
%h2{3} = 'apples'; # throws exception
CATCH { default { put .^name, ': ', .Str } };
# OUTPUT: «X::TypeCheck::Binding: Type check failed in binding to key; expected Str but got Int (3)»
my %h3{Int}; # (this time, keys must be of type Int)
%h3{42} = 4096;
say %h3.keyof; # (Int)
=head2 method of
Defined as:
method of()
Returns the type constraint for the values of the invocant. By default,
i.e., if no type constraint is given during declaration, the method
returns C<(Mu)>.
my %h1 = 'apples' => 3, 'oranges' => 7; # (no type constraint specified)
say %h1.of; # OUTPUT: «(Mu)»
my Int %h2 = 'oranges' => 7; # (values must be of type Int)
say %h2.of; # OUTPUT: «(Int)»
=head2 routine dynamic
Defined as:
method dynamic(--> Bool:D)
Returns C<True> if the invocant has been declared with the
L<is dynamic|/routine/is dynamic> trait.
my %a;
say %a.dynamic; # OUTPUT: «False»
my %b is dynamic;
say %b.dynamic; # OUTPUT: «True»
If you declare a variable with the C<*> twigil C<is dynamic> is implied.
my %*b;
say %*b.dynamic; # OUTPUT: «True»
Note that in the L<Scalar|/type/Scalar> case you have to use the C<VAR> method
in order to get correct information.
my $s is dynamic = %('apples' => 5);
say $s.dynamic; # OUTPUT: «False» (wrong, don't do this)
say $s.VAR.dynamic; # OUTPUT: «True» (correct approach)
=head1 Subscript Adverbs
Some methods are implemented as adverbs on subscripts
(consult the L<operators|/language/operators#postcircumfix_{_}> documentation
for more information).
=head2 C<:exists>
The adverb C<:exists> returns C<Bool::True> if a key exists in the Hash. If more
than one key is supplied it returns a C<List> of C<Bool>.
my %h = a => 1, b => 2;
say %h<a>:exists; # OUTPUT: «True»
say %h<a b>:exists; # OUTPUT: «(True True)»
=head2 C<:delete>
Use C<:delete> to remove a C<Pair> from the C<Hash>.
my %h = a => 1;
say %h; # OUTPUT: «{a => 1}»
say %h.elems; # OUTPUT: «1»
%h<a>:delete;
say %h; # OUTPUT: «{}»
say %h.elems; # OUTPUT: «0»
=head2 C<:p>
The adverb C<:p> returns a C<Pair> or a List of C<Pair> instead of just the
value.
my %h = a => 1, b => 2;
say %h<a>:p; # OUTPUT: «a => 1»
say %h<a b>:p; # OUTPUT: «(a => 1 b=> 2)»
=head2 C<:v> and C<:k>
The adverbs C<:v> and C<:k> return the key or value or a list thereof.
my %h = a => 1, b => 2;
say %h<a>:k; # OUTPUT: «a»
say %h<a b>:k; # OUTPUT: «(a b)»
The adverb C<:kv> returns a list of keys and values.
my %h = a => 1, b => 2, c => 3;
say %h<a c>:kv; # OUTPUT: «(a 1 c 3)»
You can also use the adverbs without knowing anything about the hash by using
empty angle brackets in which case all the keys and values will be listed:
my %h1 = a => 1;
my %h2 = a => 1, b => 2;
say %h1<>:k; # OUTPUT: «(a)»
say %h1<>:v; # OUTPUT: «(1)»
say %h2<>:k; # OUTPUT: «(a b)»
say %h2<>:v; # OUTPUT: «(1 2)»
=end pod
# vim: expandtab softtabstop=4 shiftwidth=4 ft=perl6