Categories

Posts in this category

Sat, 08 May 2010

List.classify


Permanent link

Yesterday I implement a nice Perl 6 built-in called classify.

Just like map it takes a closure and a list (or can be called as a method on a list). Unlike map it doesn't just return the values from the closure calls, but instead it constructs Pair objects from them, and groups them by equal keys. Here's one example:

say <red brown blue yellow black>.classify({ $_.substr(0, 1)}).perl;
# output:
# ("y" => ["yellow"], "b" => ["brown", "blue", "black"], "r" => ["red"])

This takes a list of color names, and groups them by their first letter. It returns a list of pairs, of which the key is always the first character (returned by the closure), the value is an array of the input values that have this first character.

Of course you can assign the result to a hash, and index by key you're interested in:

my %h = <red brown blue yellow black>.classify({ $_.substr(0, 1)});
say %h<b>.join(', ');
# output:
# brown, blue, black

So far I haven't come up with a real-world use case for classify, but I strongly suspect I'll run across one soon, and I kinda like the function.

Have you written any code lately where such a built-in would have been beneficial?

[/perl-6] Permanent link