Course of Raku / Addendum 🆕 / Flow and functions / Control flow and logic / Exercises / Sign and parity
Solution: Sign and parity
Here is a possible solution to the task.
Code
for -4, 0, 7 -> $n {
my $sign = $n < 0 ?? 'negative' !! $n == 0 ?? 'zero' !! 'positive';
my $parity = $n %% 2 ?? 'even' !! 'odd';
say "$n is $sign and $parity";
}🦋 You can find the source code in the file classify-number.raku.
Output
-4 is negative and even
0 is zero and even
7 is positive and oddComments
The sign is chosen with a chained ternary:
negativewhen below zero, otherwisezerowhen equal, otherwisepositive.$n %% 2tests divisibility by two, so it is true for even numbers and false for odd ones. (0counts as even.)
Course navigation
← Sign and parity | Leap years →