Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 0 sometimes Numeric and sometimes not Numeric?

Tags:

raku

Why is 0 sometimes Numeric and sometimes not Numeric?

my @numbers = -1, 0, 1, 'hello';
.say for @numbers.grep( Numeric );
say "====";
for @numbers -> $n {
    say $n if $n.Numeric;
}

#-1
#0
#1
#====
#-1
#1
like image 587
sid_com Avatar asked Sep 06 '25 03:09

sid_com


1 Answers

The problem is in your interpretation of $n.Numeric. You appear to think that it returns a Bool to indicate whether something is Numeric (although your own example shows otherwise).

In any case, $n.Numeric COERCES to a Numeric value. But since 0 is already a Numeric value (as your grep example shows), it is actually a no-op.

Then why doesn't show it? Well, for the simple reason that 0.Bool is False, and 1.Bool and (-1).Bool are True. So in the if statement:

say $n if $n.Numeric;

0 will not be shown, because if conceptually coerces to Bool under the hood. And this will not fire, because 0.Numeric.Bool is False.

You probably wanted to do

say $n if $n ~~ Numeric;

THAT would test if $n has a Numeric value in it.

like image 129
Elizabeth Mattijsen Avatar answered Sep 07 '25 22:09

Elizabeth Mattijsen