method classify

Documentation for method classify assembled from the following types:

class Any

From Any

(Any) method classify

Defined as:

method classify(&mapper -->Hash:D)

Coerces the invocant to a list by applying its .list method and uses List.classify on it.

say Any.classify({ $_ }); # OUTPUT: «{(Any) => [(Any)]}␤» 

class List

From List

(List) routine classify

Defined as:

multi method classify($test:$into!:&as)
multi method classify($test:&as)
multi sub classify($test+items:$into!*%named )
multi sub classify($test+items*%named )

Transforms a list of values into a hash representing the classification of those values; each hash key represents the classification for one or more of the incoming list values, and the corresponding hash value contains an array of those list values classified into the category of the associated key. $test will be an expression that will produce the hash keys according to which the elements are going to be classified.

Example:

say classify { $_ %% 2 ?? 'even' !! 'odd' }, (17632);
# OUTPUT: «{even => [6 2], odd => [1 7 3]}␤» 
say ('hello'122/742'world').classify: { .Str.chars };
# OUTPUT: «{1 => [1], 2 => [42], 5 => [hello world], 8 => [3.142857]}␤» 

It can also take :as as a named parameter, transforming the value before classifying it:

say <Innie Minnie Moe>.classify{ $_.chars }:as{ lc $_ });
# OUTPUT: «{3 => [moe], 5 => [innie], 6 => [minnie]}␤» 

This code is classifying by number of characters, which is the expression that has been passed as $test parameter, but the :as block lowercases it before doing the transformation. The named parameter :into can also be used to classify into a newly defined variable:

<Innie Minnie Moe>.classify{ $_.chars }:as{ lc $_ }:intomy %words{Int} ) );
say %words# OUTPUT: «{3 => [moe], 5 => [innie], 6 => [minnie]}␤» 

We are declaring the scope of %words{Int} on the fly, with keys that are actually integers; it gets created with the result of the classification.