Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Introduce :as parameter to classify
Use case:
my %h = (a => 1, a => 2, b=> 3).classify(*.key, :what(*.value)); say %h.perl
{:a([1, 2]), :b([3])}<>

Inspired by smls++'s comments at:
  http://irclog.perlgeek.de/perl6/2015-05-24#i_10648933
  • Loading branch information
lizmat committed May 24, 2015
1 parent 800f703 commit 922bcf0
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 11 deletions.
8 changes: 4 additions & 4 deletions src/core/Any.pm
Expand Up @@ -155,11 +155,11 @@ my class Any { # declared in BOOTSTRAP
multi method roll($n) { self.list.roll($n) }

proto method classify(|) is nodal { * }
multi method classify($test) {
Hash.^parameterize(Any,Any).new.classify-list( $test, self.list );
multi method classify($test, |c) {
Hash.^parameterize(Any,Any).new.classify-list( $test, self.list, |c );
}
multi method classify($test, :$into!) {
( $into // $into.new ).classify-list( $test, self.list );
multi method classify($test, :$into!, |c) {
( $into // $into.new ).classify-list( $test, self.list, |c );
}

proto method categorize(|) is nodal { * }
Expand Down
31 changes: 24 additions & 7 deletions src/core/Hash.pm
Expand Up @@ -129,7 +129,7 @@ my class Hash { # declared in BOOTSTRAP
}

proto method classify-list(|) { * }
multi method classify-list( &test, @list ) {
multi method classify-list( &test, @list, :&as ) {
fail X::Cannot::Infinite.new(:action<.classify>) if @list.infinite;
if @list {

Expand All @@ -141,22 +141,39 @@ my class Hash { # declared in BOOTSTRAP
my $hash = self;
$hash = $hash{$_} //= self.new for @keys;
nqp::push(
nqp::p6listitems(nqp::decont($hash{$last} //= [])), $l );
nqp::p6listitems(nqp::decont($hash{$last} //= [])),
&as ?? as($l) !! $l
);
}
}

# simple classify with to store a specific value
elsif &as {
@list.map: {
nqp::push(
nqp::p6listitems(nqp::decont(self{test $_} //= [])),
as($_)
)
}
}

# just a simple classify
else {
@list.map: { nqp::push( nqp::p6listitems(nqp::decont(self{test $_} //= [])), $_ ) }
@list.map: {
nqp::push(
nqp::p6listitems(nqp::decont(self{test $_} //= [])),
$_
)
}
}
}
self;
}
multi method classify-list( %test, $list ) {
samewith( { %test{$^a} }, $list );
multi method classify-list( %test, $list, |c ) {
samewith( { %test{$^a} }, $list, |c );
}
multi method classify-list( @test, $list ) {
samewith( { @test[$^a] }, $list );
multi method classify-list( @test, $list, |c ) {
samewith( { @test[$^a] }, $list, |c );
}

proto method categorize-list(|) { * }
Expand Down

0 comments on commit 922bcf0

Please sign in to comment.