Can I change the values ​​as I classify a Perl 6 list?

The List.classify method can convert the list to a hash with some definition that I define. The result of this 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;

Hash values ​​are lists of lists, because the source tings he classified were lists:

{
Amelia => [(Amelia 1) (Amelia 2) (Amelia 3)],
Camelia => [(Camelia 5) (Camelia 6) (Camelia 7)]
}

But I really want this:

{
Amelia => ( 1 2 3 ),
Camelia => ( 5 6 7 )
}

I could do some extra work, but this seems 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;
+6
source share
2 answers

You can use the adverb :as:

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, not yet documented .

+9
source

:into, , , classify-list Hash ( - List):

my @list = (
    <Camelia 5>,
    <Camelia 6>,
    <Camelia 7>,
    <Amelia 1>,
    <Amelia 2>,
    <Amelia 3>
    );

@list.classify: *.[0], :into(my %hash), :as( *.[1] );

say %hash;

, , , , , :into. , :

 my %hash = Hash.new.classify-list: *.[0], @list, :as( *.[1] );
+3

All Articles