List seems to be reused but bare value works fine

114 Views Asked by At

This:

my %dict;
my $counter = 0;
for ^5 -> $digit {
        %dict{$digit} = ($counter,);
        $counter += 1;
}
say %dict;

gives me this: {0 => (5), 1 => (5), 2 => (5), 3 => (5), 4 => (5)}, but I'd expect this: {0 => (0), 1 => (1), 2 => (2), 3 => (3), 4 => (4)} Assigning a bare value, an array or hash works as I'd expect.

1

There are 1 best solutions below

0
Rawley Fowler On BEST ANSWER

This happens because ($counter,) is lazy (probably??). It's a list, you'll observe the same issue when you do List.new($counter). So the creation isn't truly evaluated until you print the map. If you change to a non lazy data structure ie. an Array, using [$counter,] or Array.new($counter). It should work as you expect.

my %dict;
my $counter = 0;
for ^5 -> $digit {
        %dict{$digit} = [$counter,];
        $counter += 1;
}
say %dict;

Prints:

{0 => [0], 1 => [1], 2 => [2], 3 => [3], 4 => [4]}