Course of Raku / Addendum 🆕 / Flow and functions / Subroutines and functional style / Exercises / Sort by two keys
Solution: Sort by two keys
Here is a possible solution to the task.
Code
my @people =
{ name => 'Anna', age => 30 },
{ name => 'Bob', age => 25 },
{ name => 'Cara', age => 30 };
for @people.sort({ .<age>, .<name> }) -> %person {
say "%person<name> (%person<age>)";
}🦋 You can find the source code in the file sort-by-two-keys.raku.
Output
Bob (25)
Anna (30)
Cara (30)Comments
When a
.sortblock returns a list, Raku compares by the first element, then the second — so{ .<age>, .<name> }sorts by age first and uses the name only to break ties.Anna and Cara share age
30, so they are ordered alphabetically; Bob, being younger, comes first.