I'm struggling to understand why the zip-add Z+
operator does not work on some cases.
I have some 2-element lists that I'd like to sum.
These work as expected whether I use lists or arrays:
say (1, 2) Z+ (3, 4) # (4, 6)
say [1, 2] Z+ (3, 4) # (4, 6)
say [1, 2] Z+ [3, 4] # (4, 6)
say (1, 2) Z+ [3, 4] # (4, 6)
Now we will do the same thing but I'll change the right operand with a value stored elsewhere. In this case I have an array of lists:
my @foo = (1,1), (2,2);
say @foo.WHAT; # (Array)
say @foo[1].WHAT; # (List)
say @foo[1]; # (2,2)
say (3,3) Z+ @foo[1]; # (5) ???
Which gives the unexpected (at least for me :)) result of (5)
.
There are a couple of ways to fix this.
First one is to force the got element to be a list:
my @foo = (1,1), (2,2);
say @foo.WHAT; # (Array)
say @foo[1].WHAT; # (List) <== It was already a list, but...
say @foo[1]; # (2,2)
say (3,3) Z+ @foo[1].list; # <== changed. (5,5)
And the other one is change the @foo
definition to be a list instead of an array (either by is List
or by binding :=
the value)
my @foo is List = (1,1), (2,2); # <=== Changed
say @foo.WHAT; # (Array)
say @foo[1].WHAT; # (List) <== It was already a list
say @foo[1]; # (2,2)
say (3,3) Z+ @foo[1]; # (5,5)
Why the first case didn't work?