class SetHash

Mutable collection of distinct objects

class SetHash does Setty { }

A SetHash is a mutable set, meaning a collection of distinct elements in no particular order. (For immutable sets, see Set instead.)

Objects/values of any type are allowed as set elements. Within a Set, every element is guaranteed to be unique (in the sense that no two elements would compare positively with the === operator):

my $fruits = <peach apple orange apple apple>.SetHash;

say $fruits.elems;      # 3
say $fruits.keys.sort;  # apple orange peach

SetHashes can be treated as object hashes using the { } postcircumfix operator, which returns the value True for keys that are elements of the set, and False for keys that aren't. Assigning a value that boolifies to True or False, respectively, can be used to add or remove a set element:

say $fruits<apple>;     # True
say $fruits<kiwi>;      # False

$fruits<apple kiwi> = False, True;
say $fruits.keys.sort;  # kiwi orange peach

Creating SetHash objects

SetHashes can be composed using SetHash.new. Any positional parameters, regardless of their type, become elements of the set:

my $n = SetHash.new: "zero" => 0, "one" => 1, "two" => 2;
say $n.keys.perl;        # ("zero" => 0, "one" => 1, "two" => 2).list
say $n.keys.map(&WHAT);  # (Pair) (Pair) (Pair)

Alternatively, the .SetHash coercer (or its functional form, SetHash()) can be called on an existing object to coerce it to a SetHash. Its semantics depend on the type and contents of the object. In general it evaluates the object in list context and creates a set with the resulting items as elements, although for Hash-like objects or Pair items, only the keys become elements of the set - and keys mapped to values which boolify to False are skipped:

my $n = ("zero" => 0, "one" => 1, "two" => 2).SetHash;
say $n.keys.perl;        # ("one", "two").list
say $n.keys.map(&WHAT);  # (Str) (Str)

Operators

Perl 6 provides common set operators, which can take SetHashes (or any other collections) as input, although result sets are returned as immutable Sets. For example:

my ($a, $b) = SetHash.new(1, 2, 3), SetHash.new(2, 4);

say $a (<) $b;  # False
say $a (&) $b;  # set(2)
say $a (^) $b;  # set(1, 3, 4)

# Unicode versions:
say $a ⊂ $b;  # False
say $a ∩ $b;  # set(2)
say $a ⊖ $b;  # set(1, 3, 4)

See setbagmix#Set/Bag Operators for a complete list of set operators with detailed explanations.

See Also

Sets, Bags, and Mixes

Type graph

Below you should see an image showing the type relations for SetHash. If not, try the PNG version.

perl6-type-graph SetHash SetHash Any Any SetHash->Any Setty Setty SetHash->Setty Mu Mu Any->Mu Associative Associative QuantHash QuantHash QuantHash->Associative Setty->QuantHash

Methods supplied by role Setty

SetHash does role Setty, which provides the following methods:

method grab

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.

method grabpairs

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.

method pick

multi method pick($count = 1)

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

method roll

multi method roll($count = 1)

Returns a lazy list of $count elements, each randomly selected from the set. Each random choice is made independently, like a separate die roll where each die face is a set element.

If * is passed as $count, the list is infinite.

method keys

Returns a list of all elements of the set.

method values

Returns a list containing as many True values as the set has elements.

method kv

Returns a list of the set's elements and True values interleaved.

method elems

method elems(--> Int)

The number of elements of the set.

method total

method total(--> Int)

The total of all the values of the QuantHash object. For a Setty object, this is just the number of elements.

method ACCEPTS

method ACCEPTS($other)

Returns True if $other and self contain all the same elements, and no others.

Methods supplied by class Any

SetHash inherits from class Any, which provides the following methods:

method ACCEPTS

multi method ACCEPTS(Any:D: Mu $other)

Returns True if $other === self (i.e. it checks object identity).

method any

Interprets the invocant as a list and creates an any-Junction from it.

method all

Interprets the invocant as a list and creates an all-Junction from it.

method one

Interprets the invocant as a list and creates an one-Junction from it.

method none

Interprets the invocant as a list and creates an none-Junction from it.

Methods supplied by class Mu

SetHash inherits from class Mu, which provides the following methods:

method Str

multi method Str()   returns Str

Returns a string representation of the invocant, intended to be machine readable.

method clone

method clone(*%twiddles)

Creates a shallow clone of the invocant. If named arguments are passed to it, their values are used in every place where an attribute name matches the name of a named argument.

method new

multi method new(*%attrinit)

Default method for constructing (create + initialize) new objects of a class. This method expects only named arguments which are then used to initialize attributes with accessors of the same name.

Classes may provide their own new method to override this default.

method bless

method bless(*%attrinit) returns Mu:D

Lower-level object construction method than new.

Creates a new object of the same type as the invocant, uses the named arguments to initialize attributes, and returns the created object.

You can use this method when writing custom constructors:

class Point {
    has $.x;
    has $.y;
    multi method new($x, $y) {
        self.bless(:$x, :$y);
    }
}
my $p = Point.new(-1, 1);

(Though each time you write a custom constructor, remember that it makes subclassing harder).

method CREATE

method CREATE() returns Mu:D

Allocates a new object of the same type as the invocant, without initializing any attributes.

method print

multi method print() returns Bool:D

Prints value to $*OUT after stringification using .Str method without newline at end.

method say

multi method say() returns Bool:D

Prints value to $*OUT after stringification using .gist method with newline at end.

method ACCEPTS

multi method ACCEPTS(Mu:U: $other)

Performs a type check. Returns True if $other conforms to the invocant (which is always a type object or failure).

This is the method that is triggered on smart-matching against type objects, for example in if $var ~~ Int { ... }.

method WHICH

multi method WHICH() returns ObjAt:D

Returns an object of type ObjAt which uniquely identifies the object. Value types override this method which makes sure that two equivalent objects return the same return value from WHICH.