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

  • A+
Category:Languages

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) > $b.total 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} > %b.total 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:

> %b.Bag.total 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 %b.total 

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 %b.total 

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.

Comment

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