Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I modify values as I classify a Perl 6 list?

Tags:

list

hash

raku

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;
like image 534
brian d foy Avatar asked Jul 07 '17 17:07

brian d foy


1 Answers

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.)

like image 97
smls Avatar answered Jan 04 '23 16:01

smls