class Set

Immutable collection of distinct objects

class Set does Setty { }

A Set is an immutable set, meaning a collection of distinct elements in no particular order. (For mutable sets, see SetHash 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 = set <peach apple orange apple apple>;

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

Sets 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:

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

Creating Set objects

Sets can be composed using the set subroutine (or Set.new, for which it is a shorthand). Any positional parameters, regardless of their type, become elements of the set:

my $n = set "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 .Set coercer (or its functional form, Set()) can be called on an existing object to coerce it to a Set. 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).Set;
say $n.keys.perl;        # ("one", "two").list
say $n.keys.map(&WHAT);  # (Str) (Str)

Furthermore, you can get a Set by using set operators (see next section) on objects of other types such as List, which will internally call .Set on them before performing the operation. Be aware of the tight precedence of those operators though, which may require you to use parens around arguments:

say (1..5) (^) 4;  # set(1, 2, 3, 5)

Operators

Perl 6 provides common set operators, which can take Sets (or any other collections) as input, and return result sets as new Set objects. For example:

my ($a, $b) = set(1, 2, 3), set(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 Set/Bag Operators for a complete list of set operators with detailed explanations.

Subroutines

sub set

sub set(*@args --> Set)

Creates a Set from the given @args

See Also

Sets, Bags, and Mixes

Type graph

Below you should see a clickable image showing the type relations for Set that links to the documentation pages for the related types. If not, try the PNG version instead.

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

Routines supplied by role Setty

Set 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.

Routines supplied by class Any

Set 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).

Many built-in types override this for more specific comparisons

method any

method any() returns Junction:D

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

say so 2 == <1 2 3>.any;        # True
say so 5 == <1 2 3>.any;        # False

method all

method all() returns Junction:D

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

say so 1 < <2 3 4>.all;         # True
say so 3 < <2 3 4>.all;         # False

method one

method one() returns Junction:D

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

say so 1 == (1, 2, 3).one;      # True
say so 1 == (1, 2, 1).one;      # False

method none

method none() returns Junction:D

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

say so 1 == (1, 2, 3).none;     # False
say so 4 == (1, 2, 3).none;     # True

method list

Interprets the invocant as a list, and returns that List.

say so 42.list.^name;           # List
say so 42.list.elems;           # 1

method flat

Interprets the invocant as a list, flattens it, and returns that list.

say ((1, 2), (3)).elems;        # 2
say ((1, 2), (3)).flat.elems;   # 3

method eager

Interprets the invocant as a list, evaluates it eagerly, and returns that list.

say (1..10).eager;              # 1 2 3 4 5 6 7 8 9 10

method elems

Interprets the invocant as a list, and returns the number of elements in the list.

say 42.elems;                   # 1
say <a b c>.elems;              # 3

method end

Interprets the invocant as a list, and returns the last index of that list.

say 6.end;                      # 0
say <a b c>.end;                # 2

method pairup

method pairup() returns List

Interprets the invocant as a list, and constructs a list of pairs from it, in the same way that assignment to a Hash does. That is, it takes two consecutive elements and constructs a pair from them, unless the item in the key position already is a pair (in which case the pair is passed is passed through, and the next list item, if any, is considered to be a key again).

say (a => 1, 'b', 'c').pairup.perl;     # ("a" => 1, "b" => "c").list

sub exit

sub exit(Int() $status = 0)

Exits the current process with return code $status.

Routines supplied by class Mu

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

routine defined

multi sub    defined(Mu) returns Bool:D
multi method defined()   returns Bool:D

Returns False on the type object, and True otherwise.

say Int.defined;                # False
say 42.defined;                 # True

Very few types (like Failure) override defined to return False even for instances:

sub fails() { fail 'oh noe' };
say fails().defined;            # False

routine Bool

multi sub    Bool(Mu) returns Bool:D
multi method Bool()   returns Bool:D

Returns False on the type object, and True otherwise.

Many built-in types override this to be False for empty collections, the empty string or numerical zeros

say Mu.Bool;                    # False
say Mu.new.Bool;                # True
say [1, 2, 3].Bool;             # True
say [].Bool;                    # False
say { 'hash' => 'full'}.Bool;   # True
say {}.Bool;                    # False

method Str

multi method Str()   returns Str

Returns a string representation of the invocant, intended to be machine readable. Method Str warns on type objects, and produces the empty string.

say Mu.Str;                     #!> use of uninitialized value of type Mu in string context

routine gist

multi sub    gist(Mu) returns Str
multi method gist()   returns Str

Returns a string representation of the invocant, optimized for fast recognition by humans.

The default gist method in Mu re-dispatches to the perl method for defined invocants, and returns the type name in parenthesis for type object invocants. Many built-in classes override the case of instances to something more specific.

gist is the method that say calls implicitly, so say $something and say $something.gist generally produce the same output.

say Mu.gist;        # (Mu)
say Mu.new.gist;    # Mu.new()

routine perl

multi sub    perl(Mu) returns Str
multi method perl()   returns Str

Returns a Perlish representation of the object (i.e., can usually be re-evaluated with EVAL to regenerate the object). The exact output of perl is implementation specific, since there are generally many ways to write a Perl expression that produces a particular value

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.

class Point2D {
    has ($.x, $.y);
    multi method gist(Point2D:D:) {
        "Point($.x, $.y)";
    }
}

my $p = Point2D.new(x => 2, y => 3);

say $p;                     # Point(2, 3)
say $p.clone(y => -5);      # Point(2, -5)

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.

new triggers an object construction mechanism that calls submethods named BUILD in each class of an inheritance hierarchy, if they exist. See the documentation on object construction for more information.

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.

say Mu.CREATE.defined;  # True

method print

multi method print() returns Bool:D

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

"abc\n".print;          # abc

method say

multi method say() returns Bool:D

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

say 42;                 # 42

method ACCEPTS

multi method ACCEPTS(Mu:U: $other)

ACCEPTS is the method that smart matching with the infix ~~ operator and given/when invokes on the right-hand side (the matcher).

The Mu:U multi performs a type check. Returns True if $other conforms to the invocant (which is always a type object or failure).

say 42 ~~ Mu;           # True
say 42 ~~ Int;          # True
say 42 ~~ Str;          # False

Note that there is no multi for defined invocants; this is to allow autothreading of junctions, which happens as a fallback mechanism when no direct candidate is available to dispatch to.

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.

say 42.WHICH eq 42.WHICH;       # True

method WHERE

method WHERE() returns Int

Returns an Int representing the memory address of the object.

method WHY

multi method WHY()

Returns the attached Pod value. For instance,

    sub cast(Spell $s)
    #= Initiate a specified spell normally
    #= (do not use for class 7 spells)
    {
	do-raw-magic($s);
    }
    say &cast.WHY;

prints

Initiate a specified spell normally (do not use for class 7 spells)

See the documentation specification for details about attaching Pod to variables, classes, functions, methods, etc.

trait is export

multi sub trait_mod:<is>(Mu:U \type, :$export!)

Marks a type as being exported, that is, available to external users.

my class SomeClass is export { }

A user of a module or class automatically gets all the symbols imported that are marked as is export.

method take

method take()

Takes the given item and passes it to the enclosing gather block.

#| randomly select numbers for lotto
my $num-selected-numbers = 6;
my $max-lotto-numbers = 49;
gather for ^$num-selected-numbers {
    take (1 .. $max-lotto-numbers).pick(1);
}.say;    #-> 32 22 1 17 32 9  (for example)

method so

method so()

Returns a Bool value representing the logical non-negation of an expression. One can use this method similarly to the English sentence: "If that is so, then do this thing". For instance,

my @args = <-a -e -b -v>;
my $verbose-selected = any(@args) eq '-v' | '-V';
if $verbose-selected.so {
    say "Verbose option detected in arguments";
} #-> Verbose option detected in arguments

method not

method not()

Returns a Bool value representing the logical negation of an expression. Thus it is the opposite of so.

my @args = <-a -e -b>;
my $verbose-selected = any(@args) eq '-v' | '-V';
if $verbose-selected.not {
    say "Verbose option not present in arguments";
} #-> Verbose option not present in arguments

Since there is also a prefix version of not, the above code reads better like so:

my @args = <-a -e -b>;
my $verbose-selected = any(@args) eq '-v' | '-V';
if not $verbose-selected {
    say "Verbose option not present in arguments";
} #-> Verbose option not present in arguments