class MixHash

Mutable collection of distinct objects with Real weights

class MixHash does Mixy { }

A MixHash is a mutable mix, meaning a collection of distinct elements in no particular order that each have a real-number weight assigned to them. (For immutable mixes, see Mix instead.)

Objects/values of any type are allowed as mix elements. Within a MixHash, items that would compare positively with the === operator are considered the same element, with a combined weight.

my $recipe = (butter => 0.22, sugar => 0.1,
              flour => 0.275, sugar => 0.02).MixHash

say $recipe.elems;      # 3
say $recipe.keys.sort;  # butter flour sugar
say $recipe.pairs.sort; # "butter" => 0.22 "flour" => 0.275 "sugar" => 0.12
say $recipe.total;      # 0.615

MixHashes can be treated as object hashes using the { } postcircumfix operator, which returns the corresponding numeric weight for keys that are elements of the mix, and 0 for keys that aren't. It can also be used to modify weights; Setting a weight to 0 automatically removes that element from the mix, and setting a weight to a non-zero number adds that element if it didn't already exist:

say $recipe<butter>;     # 0.22
say $recipe<sugar>;      # 0.12
say $recipe<chocolate>;  # 0

$recipe<butter> = 0;
$recipe<chocolate> = 0.30;
say $recipe.pairs;       # "sugar" => 0.12 "flour" => 0.275 "chocolate" => 0.3

Creating MixHash objects

MixHashes can be composed using MixHash.new. Any positional parameters, regardless of their type, become elements of the mix - with a weight of 1 for each time the parameter occurred:

my $n = MixHash.new: "a", "a", "b" => 0, "c" => 3.14;
say $n.keys.map(&WHAT);  # ((Str) (Pair) (Pair))
say $n.pairs;            # (a => 2 (c => 3.14) => 1 (b => 0) => 1)

Alternatively, the .MixHash coercer (or its functional form, MixHash()) can be called on an existing object to coerce it to a MixHash. Its semantics depend on the type and contents of the object. In general it evaluates the object in list context and creates a mix with the resulting items as elements, although for Hash-like objects or Pair items, only the keys become elements of the mix, and the (cumulative) values become the associated numeric weights:

my $n = ("a", "a", "b" => 0, "c" => 3.14).MixHash;
say $n.keys.map(&WHAT);  # ((Str) (Str))
say $n.pairs;            # (a => 2 c => 3.14)

Operators

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

See Also

Sets, Bags, and Mixes

Type graph

Type relations for MixHash
perl6-type-graph MixHash MixHash Any Any MixHash->Any Mixy Mixy MixHash->Mixy Mu Mu Any->Mu Associative Associative QuantHash QuantHash QuantHash->Associative Baggy Baggy Baggy->QuantHash Mixy->Baggy

Stand-alone image: vector, raster

Routines supplied by role Mixy

MixHash does role Mixy, which provides the following methods:

method total

method total(--> Real)

Returns the sum of all the weights

mix('a', 'b', 'c', 'a', 'a', 'd').total == 6; # True
{a => 5.6, b => 2.4}.Mix.total == 8; # True

method roll

method roll($count = 1)

Similar to a Bag.roll, but with Real weights rather than integral ones.

Routines supplied by role Baggy

MixHash does role Baggy, which provides the following methods:

method grab

Defined as:

multi method grab(Baggy:D:) returns Any
multi method grab(Baggy:D: $count) returns Array: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.

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;                                   # Ford
say $cars.grab(2);                                # [Rover Rover]
say $cars.grab(*);                                # [Rover Ford]

my $breakfast = ('eggs' => 2, 'bacon' => 3).Bag;
say $breakfast.grab;                              # throws X::Immutable exception

method grabpairs

Defined as:

multi method grabpairs(Baggy:D:) returns Any
multi method grabpairs(Baggy:D: $count) returns List:D

Returns a Pair or a List 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 elements 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 => 2, bacon => 3).BagHash;
say $breakfast.grabpairs;                         # bacon => 3
say $breakfast;                                   # BagHash.new(eggs(2))
say $breakfast.grabpairs(1);                      # [eggs => 2]
say $breakfast.grabpairs(*);                      # []

my $diet = ('eggs' => 2, 'bacon' => 3).Bag;
say $diet.grabpairs;                              # throws X::Immutable exception

method pick

Defined as:

multi method pick(Baggy:D:) returns Any
multi method pick(Baggy:D: $count) returns Seq:D

Like an ordinary list pick, but returns keys of the invocant weighted by their values, as if the keys were replicated the number of times indicated by the corresponding value and then list pick used. The underlying metaphor for picking is that you're pulling colored marbles out a bag. (For "picking with replacement" see roll instead). 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.

Note that each pick invocation maintains its own private state and has no effect on subsequent pick invocations.

my $breakfast = bag <eggs bacon bacon bacon>;
say $breakfast.pick;                              # eggs
say $breakfast.pick(2);                           # (eggs bacon)

say $breakfast.total;                             # 4
say $breakfast.pick(*);                           # (bacon bacon bacon eggs)

method pickpairs

Defined as:

multi method pickpairs(Baggy:D:) returns Pair:D
multi method pickpairs(Baggy:D: $count) returns List:D

Returns a Pair or a List 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 elements weight as its value. The elements are 'picked' without replacement. 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.

Note that each pickpairs invocation maintains its own private state and has no effect on subsequent pickpairs invocations.

my $breakfast = bag <eggs bacon bacon bacon>;
say $breakfast.pickpairs;                         # eggs => 1
say $breakfast.pickpairs(1);                      # (bacon => 3)
say $breakfast.pickpairs(*);                      # (eggs => 1 bacon => 3)

method roll

Defined as:

multi method roll(Baggy:D:) returns Any:D
multi method roll(Baggy:D: $count) returns Seq:D

Like an ordinary list roll, but returns keys of the invocant weighted by their values, as if the keys were replicated the number of times indicated by the corresponding value and then list roll used. The underlying metaphor for rolling is that you're throwing $count dice that are independent of each other, which (in bag terms) is equivalent to picking a colored marble out your bag and then putting it back, and doing this $count times. In dice terms, the number of marbles corresponds to the number of sides, and the number of marbles of the same color corresponds to the number of sides with the same color. (For "picking without replacement" see pick instead).

If * is passed to $count, returns a lazy, infinite sequence of randomly chosen elements from the invocant.

my $breakfast = bag <eggs bacon bacon bacon>;
say $breakfast.roll;                                  # bacon
say $breakfast.roll(3);                               # (bacon eggs bacon)

my $random_dishes := $breakfast.roll(*);
say $random_dishes[^5];                               # (bacon eggs bacon bacon bacon)

method pairs

Defined as:

method pairs(Baggy:D:) returns Seq:D

Returns all elements and their respective weights as a Seq of Pairs where the key is the element itself and the value is the weight of that element.

my $breakfast = bag <bacon eggs bacon>;
my $seq = $breakfast.pairs;
say $seq.sort;                                    # (bacon => 2 eggs => 1)

method antipairs

Defined as:

method antipairs(Baggy:D:) returns Seq:D

Returns all elements and their respective weights as a Seq of Pairs, where the element itself is the value and the weight of that element is the key, i.e. the opposite of method pairs.

my $breakfast = bag <bacon eggs bacon>;
my $seq = $breakfast.antipairs;
say $seq.sort;                                    # (1 => eggs 2 => bacon)

method invert

Defined as:

method invert(Baggy:D:) returns Seq:D

Returns all elements and their respective weights as a Seq of Pairs, where the element itself is the value and the weight of that element is the key, i.e. the opposite of method pairs. Except for some esoteric cases invert on a Baggy type returns the same result as antipairs.

my $breakfast = bag <bacon eggs bacon>;
my $seq = $breakfast.invert;
say $seq.sort;                                    # (1 => eggs 2 => bacon)

method classify-list

Defined as:

multi method classify-list(&test, *@list) returns Baggy:D

Transforms a list of values into a classification of those values according to &test and stores the results in the invocant which is then returned. Each key represents the classification for one or more of the incoming list values, and the corresponding value contains the number of list values classified by &test into the category of the associated key.

As an example, suppose that we have a list of Ints which we would like to classify into two categories, namely even and odd numbers. Here's one way to solve this problem:

my $b = BagHash.new();
dd $b.classify-list( { $_ %% 2 ?? 'even' !! 'odd' }, (1, 7, 6, 3, 2) );
# returns: ("even"=>2,"odd"=>3).BagHash

The printed result shows us that of the numbers in the list two were classified as even and three as odd. Note that the result doesn't show us which numbers were classified as being even or odd. If that's what you want, use the classify routine in List instead.

method categorize-list

Defined as:

multi method categorize-list(&test:(Any --> Bool), *@list) returns Baggy:D

Transforms a list of values into categorizations of those values according to &test and stores the results in the invocant which is then returned. Each key represents one possible categorization for one or more of the incoming list values, and the corresponding value contains the number of list values categorized by &test into the category of the associated key.

The signature for &test contains one parameter of type Any which simply means that &test must be able to handle arguments of the same type as those in *@list.

As an example, suppose that we have a list of Ints each of which is either even or odd and, at the same time, prime or non-prime. We want to get hold of an aggregated result which shows us how many numbers were even, odd, prime and non-prime.

my $b = BagHash.new();
dd $b.categorize-list( { $_ %% 2 ?? 'even' !! 'odd',
                         $_.is-prime ?? 'prime' !! 'not prime'
                       }, (1, 7, 6, 3, 2) );
# returns: ("non-prime"=>2,"even"=>2,"prime"=>3,"odd"=>3).BagHash

The result shows us that of the numbers in the list two were categorized as even and three as odd. In addition the result also shows that three of the numbers were also categorized as prime and two as non-prime. Note that the result doesn't show us which numbers were categorized as being even, odd, prime or non-prime. If that is what you want, use the categorize routine in List instead.

It should also be noted that, unlike classify-list, which assumes that the return value of &test is a single value, categorize-list always assumes that the return value of &test is a list of categories that are appropriate to the current value.

method keys

Defined as:

method keys(Baggy:D:) returns List:D

Returns a list of all keys in the Baggy object without taking their individual weights into account as opposed to kxxv.

my $breakfast = bag <eggs spam spam spam>;
say $breakfast.keys.sort;                        # (eggs spam)

my $n = ("a" => 5, "b" => 2).BagHash;
say $n.keys.sort;                                # (a b)

method values

Defined as:

method values(Baggy:D:) returns List:D

Returns a list of all values, i.e. weights, in the Baggy object.

my $breakfast = bag <eggs spam spam spam>;
say $breakfast.values.sort;                      # (1 3)

my $n = ("a" => 5, "b" => 2, "a" => 1).BagHash;
say $n.values.sort;                              # (2 6)

method kv

Defined as:

method kv(Baggy:D:) returns List:D

Returns a list of keys and values interleaved.

my $breakfast = bag <eggs spam spam spam>;
say $breakfast.kv;                                # (spam 3 eggs 1)

my $n = ("a" => 5, "b" => 2, "a" => 1).BagHash;
say $n.kv;                                        # (a 6 b 2)

method kxxv

Defined as:

method kxxv(Baggy:D:) returns List:D

Returns a list of the keys of the invocant, with each key multiplied by its weight. Note that kxxv only works for Baggy types which have integer weights, i.e. Bag and BagHash.

my $breakfast = bag <spam eggs spam spam bacon>;
say $breakfast.kxxv.sort;                         # (bacon eggs spam spam spam)

my $n = ("a" => 0, "b" => 1, "b" => 2).BagHash;
say $n.kxxv;                                      # (b b b)

method elems

Defined as:

method elems(Baggy:D:) returns Int:D

Returns the number of elements in the Baggy object without taking the individual elements weight into account.

my $breakfast = bag <eggs spam spam spam>;
say $breakfast.elems;                             # 2

my $n = ("b" => 9.4, "b" => 2).MixHash;
say $n.elems;                                     # 1

method total

Defined as:

method total(Baggy:D:)

Returns the sum of weights for all elements in the Baggy object.

my $breakfast = bag <eggs spam spam bacon>;
say $breakfast.total;                             # 4

my $n = ("a" => 5, "b" => 1, "b" => 2).BagHash;
say $n.total;                                     # 8

method default

Defined as:

method default(Baggy:D:) returns Int:D

Returns zero.

my $breakfast = bag <eggs bacon>;
say $breakfast.default;                           # 0

method hash

Defined as:

method hash(Baggy:D:) returns Hash:D

Returns a Hash where the elements of the invocant are the keys and their respective weights the values;

my $breakfast = bag <eggs bacon bacon>;
my $h = $breakfast.hash;
say $h.WHAT;                                      # (Hash)
say $h;                                           # {bacon => 2, eggs => 1}

method Bool

Defined as:

method Bool(Baggy:D:) returns Bool:D

Returns True if the invocant contains at least one element.

my $breakfast = ('eggs' => 1).BagHash;
say $breakfast.Bool;                              # True   (since we have one element)
$breakfast<eggs> = 0;                             # weight == 0 will lead to element removal
say $breakfast.Bool;                              # False

method Set

Defined as:

method Set() returns Set:D

Returns a Set whose elements are the keys of the invocant.

my $breakfast = (eggs => 2, bacon => 3).BagHash;
say $breakfast.Set;                               # set(bacon, eggs)

method SetHash

Defined as:

method SetHash() returns SetHash:D

Returns a SetHash whose elements are the keys of the invocant.

my $breakfast = (eggs => 2, bacon => 3).BagHash;
my $sh = $breakfast.SetHash;
say $sh.WHAT;                                     # (SetHash)
say $sh.elems;                                    # 2

method ACCEPTS

Defined as:

method ACCEPTS($other) returns Bool:D

Used in smart-matching if the right-hand side is a Baggy.

If the right hand side is the type object, i.e. Baggy, the method returns True if $other does Baggy otherwise False is returned.

If the right hand side is a Baggy object, True is returned only if $other has the same elements, with the same weights, as the invocant.

my $breakfast = bag <eggs bacon>;
say $breakfast ~~ Baggy;                            # True
say $breakfast.does(Baggy);                         # True

my $second-breakfast = (eggs => 1, bacon => 1).Mix;
say $breakfast ~~ $second-breakfast;                # True

my $third-breakfast = (eggs => 1, bacon => 2).Bag;
say $second-breakfast ~~ $third-breakfast;          # False

Routines supplied by class Any

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

method ACCEPTS

Defined as:

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

Usage:

EXPR.ACCEPTS(EXPR);

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

Many built-in types override this for more specific comparisons

method any

Defined as:

method any() returns Junction:D

Usage:

LIST.any

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

Defined as:

method all() returns Junction:D

Usage:

LIST.all

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

Defined as:

method one() returns Junction:D

Usage:

LIST.one

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

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

method none

Defined as:

method none() returns Junction:D

Usage:

LIST.none

Interprets the invocant as a list and creates a 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 42.list.^name;           # List
say 42.list.elems;           # 1

method push

The method push is defined for undefined invocants and allows for autovivifying undefined to an empty Array, unless the undefined value implements Positional already. The argument provided will then be pushed into the newly created Array.

my %h;
dd %h<a>; # Any (and therefor undefined)
%h<a>.push(1); # .push on Any
dd %h; # «Hash %h = {:a($[1])}␤» # please note the Array

routine reverse

Defined as:

multi sub    reverse(*@list ) returns List:D
multi method reverse(List:D:) returns List:D

Usage:

reverse(LIST)
LIST.reverse

Returns a list with the same elements in reverse order.

Note that reverse always refers to reversing elements of a list; to reverse the characters in a string, use flip.

Examples:

say <hello world!>.reverse      # (world! hello)
say reverse ^10                 # (9 8 7 6 5 4 3 2 1 0)

method sort

Sorts iterables with infix:<cmp> or given code object and returns a new List.

Examples:

say <b c a>.sort;                           # (a b c)
say 'bca'.comb.sort.join;                   # abc
say 'bca'.comb.sort({$^b cmp $^a}).join;    # cba
say '231'.comb.sort(&infix:«<=>»).join;     # 123

method map

Defined as:

proto method map(|) is nodal { * }
multi method map(\SELF: &block;; :$label, :$item)
multi method map(HyperIterable:D: &block;; :$label)

map will iterate over the invocant and apply the number of positional parameters of the code object from the invocant per call. The returned values of the code object will become elements of the returned Seq.

method deepmap

Defined as:

method deepmap(&block -->List) is nodal

deepmap will apply &block to each element and return a new List with the return values of &block, unless the element does the Iterable role. For those elements deepmap will descend recursively into the sublist.

dd [[1,2,3],[[4,5],6,7]].deepmap(*+1);
# OUTPUT«[[2, 3, 4], [[5, 6], 7, 8]]␤»

method duckmap

Defined as:

method duckmap(&block) is rw is nodal

duckmap will apply &block on each element and return a new list with defined return values of the block. For undefined return values, duckmap will try to descend into the element if that element implements Iterable.

my @a = [1,[2,3],4];
dd @a.duckmap({ $_ ~~ Int ?? $_++ !! Any });
# OUTPUT«(1, (2, 3), 4)␤»

method flat

Interprets the invocant as a list, flattens it, and returns that list. Please note that .flat will not solve the halting problem for you. If you flat an infinite list .flat may return that infinite list, eating all your RAM in the process.

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

Please not that flat is not recursing into sub lists. You have to recurse by hand or reconsider your data structures. A single level of nesting can often be handled with destructuring in signatures. For deeper structures you may consider gather/take to create a lazy list.

my @a = [[1,2,3],[[4,5],6,7]];
sub deepflat(@a){
    gather for @a {
        take ($_ ~~ Iterable ?? deepflat($_).Slip !! $_)
    }
};
dd deepflat(@a);'
# OUTPUT«(1, 2, 3, 4, 5, 6, 7).Seq␤»

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")).Seq

sub exit

sub exit(Int() $status = 0)

Exits the current process with return code $status.

Routines supplied by class Mu

MixHash 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 isa

multi method isa(Mu $type)      returns Bool:D
multi method isa(Str:D $type)   returns Bool:D

Returns True if the invocant is an instance of class $type, a subset type or a derived class (through inheritance) of $type.

my $i = 17;
say $i.isa("Int");   # True
say $i.isa(Any);     # True

A more idiomatic way to do this is to use the smartmatch operator ~~ instead.

my $s = "String";
say $s ~~ Str;       # True

routine does

method does(Mu $type)      returns Bool:D

Returns True if and only if the invocant conforms to type $type.

my $d = Date.new('2016-06-03');
say $d.does(Dateish);             # True    (Date does role Dateish)
say $d.does(Any);                 # True    (Date is a subclass of Any)
say $d.does(DateTime);            # False   (Date is not a subclass of DateTime)

Using the smart match operator ~~ is a more idiomatic alternative.

my $d = Date.new('2016-06-03');
say $d ~~ Dateish;                # True
say $d ~~ Any;                    # True
say $d ~~ DateTime;               # 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. As such lists will be truncated at 100 elements. Use .perl to get all elements.

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 that may truncate output.

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 put

multi method put() returns Bool:D

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

"abc".put;              # abc␤

method say

multi method say() returns Bool:D

Prints value to $*OUT after stringification using .gist method with newline at end. To produce machine readable output use .put.

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.

See Exporting and Selective Importing Modules for more details.

method return

method return();

The method return will stop execution of a subroutine or method, run all relevant phasers and provide invocant as a return value to the caller. If a return type constraint is provided it will be checked unless the return value is Nil. A control exception is raised and can be caught with CONTROL.

sub f { (1|2|3).return };
dd f(); # OUTPUT«any(1, 2, 3)␤»

method return-rw

Same as method return but provides the invocant as a writeable container to the invocant.

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