total method and the sigil of a Bag variable in Perl 6

  • A+

We can use the total method to know the sum of all the weights in a Bag.

> my $b = (1,2,1).Bag Bag(1(2), 2) > $ 3 

But if we use the % sigil instead of $ for our Bag, we get an error message.

> my %b = (1,2,1).Bag {1 => 2, 2 => 1} > No such method 'total' for invocant of type 'Hash'. Did you mean 'cotan'?   in block <unit> at <unknown file> line 1 

If %b is explicitly converted to Bag before total, it works:

> 3 

The question: I used to think that with Set, Bag, SetHash etc., using the % sigil is preferable. Am I wrong?

Bind instead of assign:

my %b := (1,2,1).Bag; say 

Binding (with :=) binds an Associative value to %b.

Assigning (with =) assigns values **in***to* a Hash container that's already been bound to %b precisely because you didn't use binding.

Note that you can alternatively write:

my %b is Bag = 1,2,1; say 

With this incantation you need to use = because, by the time that operator is encountered %b has already been bound to a Bag and now you need to assign **in***to* the Bag and you get the simplicity of just providing a list of values (no explicit keys or Bag coercer/constructor necessary) because = is interpreted according to the needs of the container on its left, and a Bag knows to interpret the RHS of = as a list of keys whose occurrence count is what matters.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: