Course of Raku / Advanced / Subroutines / Calling with a colon 🆕 / Exercises / Sort with a colon
Solution: Sort with a colon
Here is a possible solution to the task.
Code
my @words = <pear fig apple kiwi>;
say @words.sort: *.chars;🦋 You can find the source code in the file colon-sort.raku.
Output
(fig pear kiwi apple)Comments
The colon passes the sort key to
sortwithout needing parentheses around it.*.charsis a Whatever expression that stands for “the number of characters of each element”.sortuses it as the key, so the words come out shortest first:fig(3), thenpearandkiwi(4), thenapple(5).pearkeeps its place ahead ofkiwibecause they are the same length andsortis stable, preserving the original order of equal keys.