The List.classify method can transform a list into a hash by some mapping that I define. The result of that mapping is the hash key and the original value
my @list = (
<Camelia 5>,
<Camelia 6>,
<Camelia 7>,
<Amelia 1>,
<Amelia 2>,
<Amelia 3>
);
my %hash = @list.classify: *.[0];
say %hash;
The hash values are lists of lists because the original thinygs it classified were lists:
{
Amelia => [(Amelia 1) (Amelia 2) (Amelia 3)],
Camelia => [(Camelia 5) (Camelia 6) (Camelia 7)]
}
But, I'd really want this:
{
Amelia => ( 1 2 3 ),
Camelia => ( 5 6 7 )
}
I could do some extra work, but that seems a bit too much work:
my @list = (
<Camelia 5>,
<Camelia 6>,
<Camelia 7>,
<Amelia 1>,
<Amelia 2>,
<Amelia 3>
);
my %hash = @list
.classify( *.[0] )
.kv
.map( {
$^a => $^b.map: *.[*-1]
} )
;
say %hash;
You can use the :as
adverb:
my @list = (
<Camelia 5>,
<Camelia 6>,
<Camelia 7>,
<Amelia 1>,
<Amelia 2>,
<Amelia 3>
);
my %hash = @list.classify: *.[0], as => *.[1];
say %hash; # {Amelia => [1 2 3], Camelia => [5 6 7]}
(Unfortunately, it doesn't seem to be documented yet.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With