class Mix

Immutable collection of distinct objects with Real weights

class Mix does Mixy { }

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

Mixes are often used for performing weighted random selections - see .roll.

Objects/values of any type are allowed as mix elements. Within a Mix, 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).Mix

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

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

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

Creating Mix objects

Mixes can be composed using the mix subroutine (or Mix.new, for which it is a shorthand). 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 = mix "a", "a", "b" => 0, "c" => 3.14;
say $n.keys.map(&WHAT);  # (Str) (Pair) (Pair)
say $n.pairs;            # "a" => 2 ("b" => 0) => 1 ("c" => 3.14) => 1

Alternatively, the .Mix coercer (or its functional form, Mix()) can be called on an existing object to coerce it to a Mix. 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).Mix;
say $n.keys.map(&WHAT);  # (Str) (Str)
say $n.pairs;            # "a" => 2 "c" => 3.14

Operators

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

sub mix

sub mix(*@args --> Mix)

Creates a new Mix from @args.

See Also

Sets, Bags, and Mixes

Type graph

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

perl6-type-graph Mix Mix Any Any Mix->Any Mixy Mixy Mix->Mixy Mu Mu Any->Mu Associative Associative QuantHash QuantHash QuantHash->Associative Baggy Baggy Baggy->QuantHash Mixy->Baggy

Routines supplied by role Mixy

Mix 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

Mix does role Baggy, which provides the following methods:

method grab

method grabpairs

method pick

method pickpairs

method roll

method classify-list

method categorize-list

method keys

method values

method kv

method elems

method total

method ACCEPTS

Routines supplied by class Any

Mix 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

Mix 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