/
Any.pod6
1429 lines (954 loc) · 43.8 KB
/
Any.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
=TITLE class Any
=SUBTITLE Thing/object
class Any is Mu {}
While L<Mu|/type/Mu> is the root of the Perl 6 class hierarchy, L<Any|/type/Any>
is the class that serves as a default base class for new classes, and as the
base class for most built-in classes.
Since Perl 6 intentionally confuses items and single-element lists, most methods
in L<Any|/type/List> are also present on class L<List|/type/Any>, and coerce to
List or a list-like type.
=head1 Methods
=head2 method ACCEPTS
Defined as:
multi method ACCEPTS(Any:D: Mu $other)
Usage:
=begin code :lang<pseudo>
EXPR.ACCEPTS(EXPR);
=end code
Returns C<True> if C<$other === self> (i.e. it checks object identity).
Many built-in types override this for more specific comparisons.
=head2 method any
Defined as:
method any(--> Junction:D)
Interprets the invocant as a list and creates an
L<any|/routine/any>-L<Junction|/type/Junction> from it.
say so 2 == <1 2 3>.any; # OUTPUT: «True»
say so 5 == <1 2 3>.any; # OUTPUT: «False»
=head2 method all
Defined as:
method all(--> Junction:D)
Interprets the invocant as a list and creates an
L<all|/routine/all>-L<Junction|/type/Junction> from it.
say so 1 < <2 3 4>.all; # OUTPUT: «True»
say so 3 < <2 3 4>.all; # OUTPUT: «False»
=head2 method one
Defined as:
method one(--> Junction:D)
Interprets the invocant as a list and creates a
L<one|/routine/one>-L<Junction|/type/Junction> from it.
say so 1 == (1, 2, 3).one; # OUTPUT: «True»
say so 1 == (1, 2, 1).one; # OUTPUT: «False»
=head2 method none
Defined as:
method none(--> Junction:D)
Interprets the invocant as a list and creates a
L<none|/routine/none>-L<Junction|/type/Junction> from it.
say so 1 == (1, 2, 3).none; # OUTPUT: «False»
say so 4 == (1, 2, 3).none; # OUTPUT: «True»
=head2 method list
Defined as:
multi method list(Any:U: --> List)
multi method list(Any:D \SELF: --> List)
Applies the infix L«C<,>|/routine/,» operator to the invocant and returns
the resulting L<List|/type/List>:
say 42.list.^name; # OUTPUT: «List»
say 42.list.elems; # OUTPUT: «1»
Subclasses of C<Any> may choose to return any I<core> type that
does the L<Positional|/type/Positional> role
from L«C<.list>|/routine/list». Use L«C<.List>|/routine/List» to
coerce specifically to L<List|/type/List>.
X<|@ list contextualizer>
C<@> can also be used as a list or C<Positional> contextualizer:
=for code
my $not-a-list-yet = $[1,2,3];
say $not-a-list-yet.perl; # OUTPUT: «$[1, 2, 3]»
my @maybe-a-list = @$not-a-list-yet;
say @maybe-a-list.^name; # OUTPUT: «Array»
In the first case, the list is I<itemized>. C<@> as a prefix puts the initial
scalar in a list context by calling C<.list> and turning it into an C<Array>.
=head2 method push
Defined as:
method push(|values --> Positional:D)
The method push is defined for undefined invocants and allows for
autovivifying undefined to an empty L<Array|/type/Array>, unless the undefined value
implements L<Positional|/type/Positional> already. The argument provided will then be pushed
into the newly created Array.
my %h;
say %h<a>; # OUTPUT: «(Any)» <-- Undefined
%h<a>.push(1); # .push on Any
say %h; # OUTPUT: «{a => [1]}» <-- Note the Array
=head2 routine reverse
Defined as:
multi sub reverse(*@list --> Seq:D)
multi method reverse(List:D: --> Seq:D)
Returns a L<Seq|/type/Seq> with the same elements in reverse order.
Note that C<reverse> always refers to reversing elements of a list;
to reverse the characters in a string, use L<flip|/routine/flip>.
Examples:
say <hello world!>.reverse; # OUTPUT: «(world! hello)»
say reverse ^10; # OUTPUT: «(9 8 7 6 5 4 3 2 1 0)»
=head2 method sort
Defined as:
multi method sort()
multi method sort(&custom-routine-to-use)
Sorts iterables with L<cmp|/routine/cmp> or given code object and returns a new
L<Seq|/type/Seq>. Optionally, takes a L<Callable|/type/Callable> as a positional
parameter, specifying how to sort.
Examples:
say <b c a>.sort; # OUTPUT: «(a b c)»
say 'bca'.comb.sort.join; # OUTPUT: «abc»
say 'bca'.comb.sort({$^b cmp $^a}).join; # OUTPUT: «cba»
say '231'.comb.sort(&infix:«<=>»).join; # OUTPUT: «123»
=head2 method map
Defined as:
multi method map(Hash:D \hash)
multi method map(Iterable:D \iterable)
multi method map(|c)
multi method map(\SELF: █; :$label, :$item)
multi sub map(&code, +values)
C<map> will iterate over the invocant and apply the number of positional
parameters of the code object from the invocant per call. The returned values
of the code object will become elements of the returned L<Seq|/type/Seq>.
The C<:$label> and C<:$item> are useful only internally, since C<for> loops get
converted to C<map>s. The C<:$label> takes an existing L<Label|/type/Label> to
label the C<.map>'s loop with and C<:$item> controls whether the iteration will
occur over C<(SELF,)> (if C<:$item> is set) or C<SELF>.
In C<sub> form, will apply the C<code> block to the C<values>, which will be
used as invocant.
The form with C<\c>, C<Iterable:D \iterable> and C<Hash:D \hash> as signatures
will fail with C<X::Cannot::Map>, and are mainly meant to catch common traps.
=head2 method deepmap
Defined as:
method deepmap(&block --> List) is nodal
C<deepmap> will apply C<&block> to each element and return a new L<List|/type/List> with
the return values of C<&block>, unless the element does the L<Iterable|/type/Iterable> role.
For those elements L<deepmap|/routine/deepmap> will descend recursively into the sublist.
say [[1,2,3],[[4,5],6,7]].deepmap(* + 1);
# OUTPUT: «[[2 3 4] [[5 6] 7 8]]»
=head2 method duckmap
Defined as:
method duckmap(&block) is rw is nodal
C<duckmap> will apply C<&block> on each element that behaves in such a way that
C<&block> can be applied. If it fails, it will descend recursively if possible,
or otherwise return the item without any transformation.
<a b c d e f g>.duckmap(-> $_ where <c d e>.any { .uc }).say;
# OUTPUT: «(a b C D E f g)»
(('d', 'e'), 'f').duckmap(-> $_ where <e f>.any { .uc }).say;
# OUTPUT: «((d E) F)»
In the first case, it is applied to C<c>, C<d> and C<e> which are the ones that
meet the conditions for the block (C<{ .uc }>) to be applied; the rest are
returned as is.
In the second case, the first item is a list that does not meet the condition,
so it's visited; that flat list will behave in the same way as the first one. In
this case:
say [[1,2,3],[[4,5],6,7]].duckmap( *² ); # OUTPUT: «[9 9]»
You can square anything as long as it behaves like a number. In this case, there
are two arrays with 3 elements each; these arrays will be converted into the
number 3 and squared. In the next case, however
say [[1,2,3],[[4,5],6.1,7.2]].duckmap( -> Rat $_ { $_²} );
# OUTPUT: «[[1 2 3] [[4 5] 37.21 51.84]]»
3-item lists are not C<Rat>, so it descends recursively, but eventually only applies the operation to those that walk (or slither, as the case may be) like a C<Rat>.
Although on the surface (and name), C<duckmap> might look similar to L<C<deepmap>|/routine/deepmap>, the latter is applied recursively regardless of the type of the item.
=head2 method nodemap
Defined as:
method nodemap(&block --> List) is nodal
C<nodemap> will apply C<&block> to each element and return a new L<List|/type/List> with
the return values of C<&block>. In contrast to L<deepmap|/routine/deepmap> it will B<not> descend
recursively into sublists if it finds elements which L<does|/routine/does> the L<Iterable|/type/Iterable> role.
say [[1,2,3], [[4,5],6,7], 7].nodemap(*+1);
# OUTPUT: «(4, 4, 8)»
say [[2, 3], [4, [5, 6]]]».nodemap(*+1)
# OUTPUT: «((3 4) (5 3))»
The examples above would have produced the exact same results if we had used
L<map|/routine/map> instead of C<nodemap>. The difference between the two lies in the
fact that L<map|/routine/map> flattens out L<slips|/type/Slip> while C<nodemap> doesn't.
say [[2,3], [[4,5],6,7], 7].nodemap({.elems == 1 ?? $_ !! slip});
# OUTPUT: «(() () 7)»
say [[2,3], [[4,5],6,7], 7].map({.elems == 1 ?? $_ !! slip});
# OUTPUT: «(7)»
=head2 method flat
Defined as:
method flat() is nodal
Interprets the invocant as a list, flattens
L<non-containerized|/language/containers> L<Iterable|/type/Iterable>s into a
flat list, and returns that list. Keep in mind L<Map|/type/Map> and
L<Hash|/type/Hash> types are L<Iterable|/type/Iterable> and so will be flattened
into lists of pairs.
say ((1, 2), (3), %(:42a)); # OUTPUT: «((1 2) 3 {a => 42})»
say ((1, 2), (3), %(:42a)).flat; # OUTPUT: «(1 2 3 a => 42)»
Note that L<Arrays|/type/Array> containerize their elements by default, and so
C<flat> will not flatten them. You can use
L<hyper method call|/language/operators#index-entry-postfix_».> to call
L«C<.List>|/routine/List» method on all the inner L<Iterables|/type/Iterable>
and so de-containerize them, so that C<flat> can flatten them:
say [[1, 2, 3], [(4, 5), 6, 7]] .flat; # OUTPUT: «([1 2 3] [(4 5) 6 7])»
say [[1, 2, 3], [(4, 5), 6, 7]]».List.flat; # OUTPUT: «(1 2 3 4 5 6 7)»
For more fine-tuned options, see L<deepmap|/routine/deepmap>,
L<duckmap|/routine/duckmap>, and
L<signature destructuring|/type/Signature#Destructuring_Parameters>
=head2 method eager
Defined as:
method eager() is nodal
Interprets the invocant as a L<List|/type/List>, evaluates it eagerly, and
returns that L<List|/type/List>.
my $range = 1..5;
say $range; # OUTPUT: «1..5»
say $range.eager; # OUTPUT: «(1 2 3 4 5)»
=head2 method elems
Defined as:
multi method elems(Any:U: --> 1)
multi method elems(Any:D:)
Interprets the invocant as a list, and returns the number of elements in the
list.
say 42.elems; # OUTPUT: «1»
say <a b c>.elems; # OUTPUT: «3»
say Whatever.elems ; # OUTPUT: «1»
It will also return 1 for classes.
=head2 method end
multi method end(Any:U: --> 0)
multi method end(Any:D:)
Interprets the invocant as a list, and returns the last index of that list.
say 6.end; # OUTPUT: «0»
say <a b c>.end; # OUTPUT: «2»
=head2 method pairup
Defined as:
multi method pairup(Any:U:)
multi method pairup(Any:D:)
Interprets the invocant as a list, and constructs a list of
L<pairs|/type/Pair> from it, in the same way that assignment to a
L<Hash|/type/Hash> does. That is, it takes two consecutive elements and
constructs a pair from them, unless the item in the key position already is a
pair (in which case the pair is passed through, and the next list item, if any,
is considered to be a key again). It returns a C<Seq> of C<Pair>s.
say (a => 1, 'b', 'c').pairup.perl; # OUTPUT: «(:a(1), :b("c")).Seq»
X<|$ (item contextualizer)>
=head2 sub item
Defined as:
multi item(\x)
multi item(|c)
multi item(Mu $a)
Forces given object to be evaluated in item context and returns the value of it.
say item([1,2,3]).perl; # OUTPUT: «$[1, 2, 3]»
say item( %( apple => 10 ) ).perl; # OUTPUT: «${:apple(10)}»
say item("abc").perl; # OUTPUT: «"abc"»
You can also use C<$> as item contextualizer.
say $[1,2,3].perl; # OUTPUT: «$[1, 2, 3]»
say $("abc").perl; # OUTPUT: «"abc"»
=head2 method Array
Defined as:
method Array(--> Array:D) is nodal
Coerces the invocant to an L<Array|/type/Array>.
=head2 method List
Defined as:
method List(--> List:D) is nodal
Coerces the invocant to L<List|/type/List>, using the L<list|/routine/list>
method.
=head2 method serial
Defined as
multi method serial()
Returns the self-reference to the instance itself:
=begin code
my $b; # defaults to Any
say $b.serial.^name; # OUTPUT: «Any»
my $breakfast = 'food';
$breakfast.serial.say; # OUTPUT: «food»
=end code
=head2 method Hash
Defined as:
multi method Hash( --> Hash:D)
Coerces the invocant to L<Hash|/type/Hash>.
=head2 method hash
Defined as:
multi method hash(Any:U:)
multi method hash(Any:D:)
When called on a type object, returns an empty L<Hash|/type/Hash>. On instances,
it is equivalent to assigning the invocant to a C<%->sigiled variable and
returning that.
Subclasses of C<Any> may choose to return any I<core> type that does the
L<Associative|/type/Associative> role from L«C<.hash>|/routine/hash». Use
L«C<.Hash>|/routine/Hash» to coerce specifically to L<Hash|/type/Hash>.
=begin code
my $d; # $d is Any
say $d.hash; # OUTPUT: {}
my %m is Map = a => 42, b => 666;
say %m.hash; # Map.new((a => 42, b => 666))
say %m.Hash; # {a => 42, b => 666}
=end code
=head2 method Slip
Defined as:
method Slip(--> Slip:D) is nodal
Coerces the invocant to L<Slip|/type/Slip>.
=head2 method Map
Defined as:
method Map(--> Map:D) is nodal
Coerces the invocant to L<Map|/type/Map>.
=head2 method Bag
Defined as:
method Bag(--> Bag:D) is nodal
Coerces the invocant to L<Bag|/type/Bag>, whereby
L<Positionals|/type/Positional> are treated as lists of values.
=head2 method BagHash
Defined as:
method BagHash(--> BagHash:D) is nodal
Coerces the invocant to L<BagHash|/type/BagHash>, whereby L<Positionals|/type/Positional>
are treated as lists of values.
=head2 method Set
Defined as:
method Set(--> Set:D) is nodal
Coerces the invocant to L<Set|/type/Set>, whereby L<Positionals|/type/Positional>
are treated as lists of values.
=head2 method SetHash
Defined as:
method SetHash(--> SetHash:D) is nodal
Coerces the invocant to L<SetHash|/type/SetHash>, whereby L<Positionals|/type/Positional>
are treated as lists of values.
=head2 method Mix
Defined as:
method Mix(--> Mix:D) is nodal
Coerces the invocant to L<Mix|/type/Mix>, whereby L<Positionals|/type/Positional>
are treated as lists of values.
=head2 method MixHash
Defined as:
method MixHash(--> MixHash:D) is nodal
Coerces the invocant to L<MixHash|/type/MixHash>, whereby L<Positionals|/type/Positional>
are treated as lists of values.
=head2 method Supply
Defined as:
method Supply(--> Supply:D) is nodal
Coerces the invocant first to a C<list> by applying its
L«C<.list>|/routine/list» method, and then to L<Supply|/type/Supply>.
=head2 method min
Defined as:
multi method min(--> Any:D)
multi method min(&filter --> Any:D)
multi sub min(+args, :&by!)
multi sub min(+args)
Coerces the invocant to L<Iterable|/type/Iterable> and returns the numerically smallest
element. In C<sub> form, the invocant is passed as an argument.
If a L<Callable|/type/Callable> positional argument is provided, each value is passed
into the filter, and its return value is compared instead of the
original value. The original value is still the one returned from
C<min>.
say (1,7,3).min(); # OUTPUT:«1»
say (1,7,3).min({1/$_}); # OUTPUT:«7»
say min(1,7,3); # OUTPUT: «1»
say min(1,7,3,:by( { 1/$_ } )); # OUTPUT: «7»
=head2 method max
Defined as:
multi method max(--> Any:D)
multi method max(&filter --> Any:D)
multi sub max(+args, :&by!)
multi sub max(+args)
Coerces the invocant to L<Iterable|/type/Iterable> and returns the numerically largest
element.
If a L<Callable|/type/Callable> positional argument is provided, each value is passed
into the filter, and the return value is compared instead of the
original value. The original value is still the one returned from
C<max>.
say (1,7,3).max(); # OUTPUT:«7»
say (1,7,3).max({1/$_}); # OUTPUT:«1»
say max(1,7,3,:by( { 1/$_ } )); # OUTPUT: «1»
say max(1,7,3); # OUTPUT: «7»
=head2 method minmax
Defined as:
multi method minmax(--> Range:D)
multi method minmax(&filter --> Range:D)
multi sub minmax(+args, :&by!)
multi sub minmax(+args)
Returns a C<Range> from the smallest to the largest element.
If a L<Callable|/type/Callable> positional argument is provided, each value is passed
into the filter, and its return value is compared instead of the
original value. The original values are still used in the returned
C<Range>.
say (1,7,3).minmax(); # OUTPUT:«1..7»
say (1,7,3).minmax({-$_}); # OUTPUT:«7..1»
say minmax(1,7,3); # OUTPUT: «1..7»
say minmax(1,7,3,:by( -* )); # OUTPUT: «7..1»
=head2 method minpairs
Defined as:
multi method minpairs(Any:D: --> Seq:D)
Calls L«C<.pairs>|/routine/pairs» and returns a L<Seq|/type/Seq> with
all of the Pairs with minimum values, as judged by the
L«C<cmp> operator|/routine/cmp»:
<a b c a b c>.minpairs.perl.put; # OUTPUT: «(0 => "a", 3 => "a").Seq»
%(:42a, :75b).minpairs.perl.put; # OUTPUT: «(:a(42),).Seq»
=head2 method maxpairs
Defined as:
multi method maxpairs(Any:D: --> Seq:D)
Calls L«C<.pairs>|/routine/pairs» and returns a L<Seq|/type/Seq> with all of the
Pairs with maximum values, as judged by the L«C<cmp>
operator|/routine/cmp»:
<a b c a b c>.maxpairs.perl.put; # OUTPUT: «(2 => "c", 5 => "c").Seq»
%(:42a, :75b).maxpairs.perl.put; # OUTPUT: «(:b(75),).Seq»
=head2 method keys
Defined as:
multi method keys(Any:U: --> List)
multi method keys(Any:D: --> List)
For defined L<Any|/type/Any> returns its L<keys|/routine/keys> after calling C<list> on it,
otherwise calls C<list> and returns it.
my $setty = Set(<Þor Oðin Freija>);
say $setty.keys; # OUTPUT: «(Þor Oðin Freija)»
See also L<C<List.keys>|/type/List#routine_keys>.
Trying the same on a class will return an empty list, since most of them
don't really have keys.
=head2 method flatmap
Defined as:
method flatmap(&block, :$label)
B<DEPRECATION NOTICE>: This method is deprecated in 6.d and will be removed in
6.e. Use C<.map> followed by C<.flat> instead.
Applies L<C<map>|/type/Any#method_map> to every element with the block and
C<Label> used as an argument and flattens out the result using C<.flat>.
say "aabbccc".comb.Mix.flatmap: "→ " ~ *; # OUTPUT: «(→ b␉2 → c␉3 → a␉2)»
In this case, the elements of the C<Mix> are itemized to key␉value, and then
mapped and flattened. Same result as
say "aabbccc".comb.Mix.map( "→ " ~ * ).flat
Which is why it is deprecated in 6.d and will be eventually eliminated in 6.e.
=head2 method roll
Defined as:
multi method roll(--> Any)
multi method roll($n --> Seq)
Coerces the invocant to a C<list> by applying its
L«C<.list>|/routine/list» method and uses
L«C<List.roll>|/type/List#routine_roll» on it.
my Mix $m = ("þ" xx 3, "ð" xx 4, "ß" xx 5).Mix;
say $m.roll; # OUTPUT: «ð»
say $m.roll(5); # OUTPUT: «(ß ß þ ß þ)»
C<$m>, in this case, is converted into a list and then a (weighted in this case)
dice is rolled on it. See also L<C<List.roll>|/type/List#routine_roll> for more
information.
=head2 method iterator
Defined as:
multi method iterator(Any:)
Returns the object as an iterator after converting it to a list. This is the
function called from the C<for> statement.
.say for 3; # OUTPUT: «3»
Most subclasses redefine this method for optimization, so it's mostly types that
do not actually iterate the ones that actually use this implementation.
=head2 method pick
Defined as:
multi method pick(--> Any)
multi method pick($n --> Seq)
Coerces the invocant to a C<list> by applying
its L«C<.list>|/routine/list» method and uses
L«C<List.pick>|/type/List#routine_pick» on it.
my Range $rg = 'α'..'ω';
say $rg.pick(3); # OUTPUT: «(β α σ)»
=head2 method skip
Defined as:
multi method skip()
multi method skip(Whatever)
multi method skip(Callable:D $w)
multi method skip(Int() $n)
Creates a L<Seq|/type/Seq> from 1-item list's iterator and uses
L«C<Seq.skip>|/type/Seq#method_skip» on it, please check that document for real
use cases; calling C<skip> without argument is equivalent to C<skip(1)>.
Calling it with C<Whatever> will return an empty iterator:
say <1 2 3>.skip(*); # OUTPUT: «()»
The multi that uses a Callable is intended mainly to be used this way:
say <1 2 3>.skip(*-1); # OUTPUT: «(3)»
Instead of throwing away the first C<$n> elements, it throws away everything
I<but> the elements indicated by the WhateverCode, in this case all but the last
one.
=head2 method prepend
Defined as:
multi method prepend(--> Array)
multi method prepend(@values --> Array)
Called with no arguments on an empty variable, it initializes it as an
empty L<Array|/type/Array>; if called with arguments, it creates an array and then
applies L«C<Array.prepend>|/type/Array#method_prepend» on it.
my $a;
say $a.prepend; # OUTPUT: «[]»
say $a; # OUTPUT: «[]»
my $b;
say $b.prepend(1,2,3); # OUTPUT: «[1 2 3]»
=head2 method unshift
Defined as:
multi method unshift(--> Array)
multi method unshift(@values --> Array)
Initializes L<Any|/type/Any> variable as empty L<Array|/type/Array> and calls
L«C<Array.unshift>|/type/Array#routine_unshift» on it.
my $a;
say $a.unshift; # OUTPUT: «[]»
say $a; # OUTPUT: «[]»
my $b;
say $b.unshift([1,2,3]); # OUTPUT: «[[1 2 3]]»
=head2 method first
Defined as:
multi method first(Bool:D $t)
multi method first(Regex:D $test, :$end, *%a)
multi method first(Callable:D $test, :$end, *%a is copy)
multi method first(Mu $test, :$end, *%a)
multi method first(:$end, *%a)
multi sub first(Bool:D $t, |)
multi sub first(Mu $test, +values, *%a)
In general, coerces the invocant to a C<list> by applying its
L«C<.list>|/routine/list» method and uses
L«C<List.first>|/type/List#routine_first» on it.
However, there are several different methods, and they have (slightly) different
behavior. Using a C<Bool> as the argument will always return a L<Failure>. Using
it as a subroutine is equivalent to using it as a method with the second
argument as the object.
The form that uses a C<$test> will return the first element that smartmatches
it, starting from the end if C<:end> is used.
say (3..33).first; # OUTPUT: «3»
say (3..33).first(:end); # OUTPUT: «33»
say (⅓,⅔…30).first( 0xF ); # OUTPUT: «15»
say first 0xF, (⅓,⅔…30); # OUTPUT: «15»
say (3..33).first( /\d\d/ ); # OUTPUT: «10»
The third and fourth example use the C<Mu $test> forms which smartmatches and
returns the first element that does. The last example uses as a test a regex for
numbers with two figures, and thus the first that meets that criterion is number
10. This last form uses the C<Callable> multi:
say (⅓,⅔…30).first( * %% 11, :end, :kv ); # OUTPUT: «(65 22)»
From version 6.d, the test can also be a C<Junction>:
say (⅓,⅔…30).first( 3 | 33, :kv ); # OUTPUT: «(8 3)»
Besides, starts from the C<:end> and returns the C<:kv> in a list; the I<key> in
this case is simply the position it occupies in the C<Seq>.
=head2 method unique
Defined as:
multi method unique()
multi method unique( :&as!, :&with! )
multi method unique( :&as! )
multi method unique( :&with! )
multi sub unique(+values, |c)
Creates a sequence of unique elements either of the object or of C<values> in
the case it's called as a C<sub>.
<1 2 2 3 3 3>.unique.say; # OUTPUT: «(1 2 3)»
say unique <1 2 2 3 3 3>; # OUTPUT: «(1 2 3)»
The C<:as> and C<:with> parameters receive functions that are used for
transforming the item before checking equality, and for checking equality, since
by default the L<C<===>|/routine/===> operator is used:
("1", 1, "1 ", 2).unique( as => Int, with => &[==] ).say; #OUTPUT: «(1 2)»
Please see L<C<List.unique>|/type/List#routine_unique> for additional examples.
=head2 method repeated
Defined as:
multi sub repeated(+values, |c)
multi method repeated()
multi method repeated( :&as!, :&with! )
multi method repeated( :&as! )
multi method repeated( :&with! )
Similarly to L<C<unique>|/type/Any#method_unique>, finds repeated elements in
C<values> (as a routine) or in the object, using the C<:as> associative argument
as a normalizing function and C<:with> as equality function.
<1 -1 2 -2 3>.repeated(:as(&abs),:with(&[==])).say; # OUTPUT: «(-1 -2)»
(3+3i, 3+2i, 2+1i).repeated(as => *.re).say; # OUTPUT: «(3+2i)»
It returns the last repeated element before normalization, as shown in the
example above. See L<C<list.repeated>|/type/List#routine_repeated> for more
examples.
=head2 method squish
Defined as:
multi method squish( :&as!, :&with = &[===] )
multi method squish( :&with = &[===] )
sub squish( +values, |c)
Similar to L<C<.repeated>|/type/Any#method_repeated>, returns the sequence of
first elements of contiguous sequences of equal elements, after normalization by
the function C<:as>, if present, and using as an equality operator the C<:with>
argument or C<===> by default.
=for code
"aabbccddaa".comb.squish.say; # OUTPUT: «(a b c d a)»
"aABbccdDaa".comb.squish( :as(&lc) ).say; # OUTPUT: «(a B c d a)»
(3+2i,3+3i,4+0i).squish( as => *.re, with => &[==]).put; #OUTPUT: «3+2i 4+0i»
As shown in the last example, a sequence can contain a single element. See
L<C<List.squish>|/type/List#routine_squish> for additional examples.
=head2 method permutations
Defined as:
method permutations(|c)
Coerces the invocant to a C<list> by applying its
L«C<.list>|/routine/list» method and uses
L«C<List.permutations>|/type/List#routine_permutations» on it.
say <a b c>.permutations;
# OUTPUT: «((a b c) (a c b) (b a c) (b c a) (c a b) (c b a))»
say set(1,2).permutations;
# OUTPUT: «((2 => True 1 => True) (1 => True 2 => True))»
=head2 method join
Defined as
method join($separator = '') is nodal
Converts the object to a list, and applies
L<C<list.join>|/type/List#routine_join> to it. Can take a separator, which is an
empty string by default.
(1..3).join.say ; # OUTPUT: «123»
<a b c>.join("❧").put; # OUTPUT: «a❧b❧c»
=head2 method categorize
Defined as:
multi method categorize()
multi method categorize(Whatever)
multi method categorize($test, :$into!, :&as)
multi method categorize($test, :&as)
multi sub categorize($test, +items, :$into!, *%named )
multi sub categorize($test, +items, *%named )
The two first forms fail with an error message.
In its simplest form, it uses a C<$test> whose result will be used as a key; the
values of the key will be an array of the elements that produced that key as a
result of the test.
=for code
say (1..13).categorize( * %% 3);
say categorize( * %% 3, 1..13)
# OUTPUT: «{False => [1 2 4 5 7 8 10 11 13], True => [3 6 9 12]}»
The C<:as> argument will normalize before categorizing
=for code
say categorize( * %% 3, -5..5, as => &abs )
# OUTPUT: «{False => [5 4 2 1 1 2 4 5], True => [3 0 3]}»
The C<$into> associative argument can be used to put the result instead of
returning a new C<Hash>
=for code
my %leap-years;
my @years = (2002..2009).map( { Date.new( $_~"-01-01" ) } );
@years.categorize( *.is-leap-year , into => %leap-years );
say %leap-years
# OUTPUT:
# «{ False
# => [2002-01-01 2003-01-01 2005-01-01 2006-01-01 2007-01-01 2009-01-01],
# True => [2004-01-01 2008-01-01]}»
The function used to categorize can return an array indicating all possible bins
their argument can be put into:
=begin code
sub divisible-by( Int $n --> Array(Seq) ) {
gather {
for <2 3 5 7> {
take $_ if $n %% $_;
}
}
}
say (3..13).categorize( &divisible-by );
# OUTPUT:
# «{2 => [4 6 8 10 12], 3 => [3 6 9 12], 5 => [5 10], 7 => [7]}»
=end code
In this case, every number in the range is classified in as many bins as it can
be divided by.
=head2 method classify
Defined as:
multi method classify()
multi method classify(Whatever)
multi method classify($test, :$into!, :&as)
multi method classify($test, :&as)
multi sub classify($test, +items, :$into!, *%named )
multi sub classify($test, +items, *%named )
The two first forms will fail. The rest include a C<$test>, which is a function
that will return a scalar for every input; these will be used as keys of a hash
whose values will be arrays with the elements that output that key for the test
function.
=for code
my @years = (2003..2008).map( { Date.new( $_~"-01-01" ) } );
@years.classify( *.is-leap-year , into => my %leap-years );
say %leap-years;
# OUTPUT: «{False => [2003-01-01 2005-01-01 2006-01-01 2007-01-01],
# True => [2004-01-01 2008-01-01]}»
Similarly to L<C<.categorize>|/type/Any#method_categorize>, elements can be
normalized by the C<Callable> passed with the C<:as> argument, and it can use
the C<:into> named argument to pass a C<Hash> the results will be classified
into; in the example above, it's defined on the fly.
=head2 method reduce
Defined as:
multi method reduce(Any:U: & --> Nil)
multi method reduce(Any:D: &with)
multi sub reduce (&with, +list)
Applying it to a class will always produce Nil.
Applies its argument (or first argument, in case it's a sub) as an operator to
all the elements in the object (or second argument), producing a single result.
The argument must be an infix operator or take, in any case, two positional
arguments.
(1..13).reduce( &[*] ).say; # OUTPUT: «6227020800»
=head2 method produce
Defined as:
multi method produce(Any:U: & --> Nil)
multi method produce(Any:D: &with)
multi sub produce (&with, +list)
This is similar to L<C<reduce>|/routine/reduce#(List)_routine_reduce>, but
returns a list with the accumulated values instead of a single result.