grab
ErrorsCollection

grab

Synthesised documentation from type/Baggy type/Supply type/Setty type/Mixy

From type/Baggy

See Original text in context

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

Like pick, a grab returns a random selection of elements, weighted by the values corresponding to each key. Unlike pick, it works only on mutable structures, e.g. BagHash. Use of grab on an immutable structure results in an X::Immutable exception. If * is passed as $count, or $count is greater than or equal to the total of the invocant, then total elements from the invocant are returned in a random sequence; i.e. they are returned shuffled.

Grabbing decrements the grabbed key's weight by one (deleting the key when it reaches 0). By definition, the total of the invocant also decreases by one, so the probabilities stay consistent through subsequent grab operations.

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

From type/Supply

See Original text in context

method grab(Supply:D: &when-done --> Supply:D)

Taps the Supply it is called on. When it is done, calls &when-done and then emits the list of values that it returns on the result Supply. If the original Supply quits, then the exception is immediately conveyed on the return Supply.

my $s = Supply.from-list(41032);
my $t = $s.grab(&sum);
$t.tap(&say);           # OUTPUT: «19␤»

From type/Setty

See Original text in context

method grab($count = 1)

Removes and returns $count elements chosen at random (without repetition) from the set.

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 in random order.

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

From type/Mixy

See Original text in context

method grab($?)

Throws an exception. The feature is not supported on the type, since there's no clear value to subtract from non-integral weights, to make it work.