|
|
| P is for Practical | |
| PerlMonks |
Perl 6 sorting (was: Re: Sort: By keys, values, and their returning values.)by moritz (Cardinal) |
| on Nov 26, 2009 at 10:50 UTC ( [id://809530] : note . print w/replies, xml ) | Need Help?? |
|
Allow me show off some Perl 6 features here.
If you use a hash in list context in Perl 6, you get a list of pairs, each holding a key and a value. Since hashes are object like everything else, you can call methods on them:
Since values are typed (ie you can ask a variable if it contains a number, a string or something entirely different), the default comparison is smart enough to compare strings with string semantics and numbers with number semantics. So if the values are numbers already, there's no need to explicitly use <=> It is even smart enough to compare pairs, so when you call %hash.sort directly, it sorts primary by key and secondary by value. What if you want to sort the keys by value? You use the built-in Schwartzian transform:
Since the block { %hash{$_} } knows its number of parameters, the sort method can find out that the block takes not two but one parameter, and sorts by the return value of the block, while still returning the original value. If you want to do that on an anonymous hash, you can sort the pairs instead:
This sorts the pairs by value, and then calls the .key method on each list item. (so >>.key is short for .map({ .key }), except that the compiler is allowed to execute the >>.key calls out of order, and parallelize them) Having Pair objects and a built-in Schwartzian transform makes sorting really simple and powerful. And Rakudo implements all of this already. Have fun experimenting!
Perl 6 - links to (nearly) everything that is Perl 6.
In Section
Seekers of Perl Wisdom
|
|
||||||||||||||||||||||||||||