Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time Warping Variable Initialization?

In the following simple for loop we create an array (@a) by incrementing a typeless variable ($n):

my @a = do for 1..3 {
    state $n;
    $n.^name, $n++;
}

say @a;

The result is "kind of" expected:

[(Any 0) (Int 1) (Int 2)]

And I say "kind of" because I've expected as the first value of $n the "undefined" value (Any).

It is like, after the first value is produced (Any) and as we increment the $n (after the first increment of $n we have a casting to an Int) there is also some time warping event in the assignment and we get also the first value to change. So we end up having the first value as 0 (zero).

Can somebody explain the exact mechanism of this behaviour?

like image 977
jakar Avatar asked Jan 24 '20 08:01

jakar


1 Answers

see Any.pm6#L519, the candidate

multi sub postfix:<++>(Mu:U $a is rw) { $a = 1; 0 }

is used. There are some another candidates for undefined values, you can try

my Bool $x; 
dd $x++; #Bool::False

my Num $y;
dd $y++; #0e0
like image 164
wamba Avatar answered Nov 01 '22 23:11

wamba