Course of Raku / Advanced / Subroutines / Multiple dispatch / Exercises / Classify the size
Solution: Classify the size
Here is a possible solution to the task.
Code
multi sub size(Int $n where $n.abs < 10) { 'small' }
multi sub size(Int $n where $n.abs < 100) { 'medium' }
multi sub size(Int $n) { 'large' }
say size(7);
say size(30);
say size(-250);🦋 You can find the source code in the file classify-sign.raku.
Output
small
medium
largeComments
All three candidates take a single
Int, so without thewhereclauses they would clash. The conditions on the first two make them distinct, and the third is the catch-all.The
whereclauses test$n.abs, so the magnitude alone decides the result and the sign is ignored.size(7)matches the first candidate (small), whilesize(-250)has an absolute value of250, which fails both conditions and falls through to the catch-all (large).The candidates are tested from the most specific to the most general — exactly the order in which they are written here.