grabpairs
ErrorsCollection

grabpairs

Synthesised documentation from type/Baggy type/Setty

From type/Baggy

See Original text in context

multi method grabpairs(Baggy:D: --> Any)
multi method grabpairs(Baggy:D: $count --> Seq:D)

Returns a Pair or a Seq of Pairs depending on the version of the method being invoked. Each Pair returned has an element of the invocant as its key and the element's weight as its value. Unlike pickpairs, it works only on mutable structures, e.g. BagHash. Use of grabpairs on an immutable structure results in an X::Immutable exception. If * is passed as $count, or $count is greater than or equal to the number of elements of the invocant, then all element/weight Pairs from the invocant are returned in a random sequence.

What makes grabpairs different from pickpairs is that the 'grabbed' elements are in fact removed from the invocant.

my $breakfast = (eggs => 2bacon => 3).BagHash;
say $breakfast.grabpairs;                         # OUTPUT: «bacon => 3␤» 
say $breakfast;                                   # OUTPUT: «BagHash.new(eggs(2))␤» 
say $breakfast.grabpairs(1);                      # OUTPUT: «(eggs => 2)␤» 
say $breakfast.grabpairs(*);                      # OUTPUT: «()␤» 
 
my $diet = ('eggs' => 2'bacon' => 3).Bag;
say $diet.grabpairs;
CATCH { default { put .^name''.Str } };
# OUTPUT: «X::Immutable: Cannot call 'grabpairs' on an immutable 'Bag'␤»

From type/Setty

See Original text in context

method grabpairs($count = 1)

Removes $count elements chosen at random (without repetition) from the set, and returns a list of Pair objects whose keys are the grabbed elements and whose values are True.

If * is passed as $count, or $count is greater than or equal to the size of the set, then all its elements are removed and returned as Pairs in the aforementioned way in random order.

Only works on mutable sets; When used on an immutable set, it results in an exception.