Search code examples
raku

List seems to be reused but bare value works fine


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.


Solution

  • 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]}