Are there cases when I have to use `elems` with an array to make it work?

Viewed 80

After reading this answer I looked through my code and found some places where I use elems with arrays.

I could remove all elems without affecting the code:

my @a = 1, 2, 3, 4, 5;
my $b = [ 1, 2, 3, 4 ];

my $i = 2;
say $i + @a.elems;
say $i + @a;

say "===============";
say @a.elems;
say 0 + @a;

say "===============";
say $b.elems / 2;
say $b / 2;

say "===============";
while state $c++ > $b.elems {
    say $c;
}
while state $d++ > $b {
    say $d;
}

That led me to wonder if there are situations where arrays have to be called with the elems function to make the code work.

1 Answers

Whenever a numeric operator sees an Iterable as one of its operands, it will call the .elems method on it. Sometimes that will result in a Failure or an Exception being thrown:

$ raku -e 'say (1 ... *) + 42'
Cannot .elems a lazy list

Mind you, using the .elems in your code has 2 advantages:

  • it makes your intention explicit, good for future maintainers
  • it will be slightly more efficient, because it will skip the operator call
Related