class Mu
The root of the Perl 6 type hierarchy.
The root of the Perl 6 type hierarchy. For the origin of the name, see https://en.wikipedia.org/wiki/Mu_%28negative%29. One can also say that there are many undefined values in Perl 6, and Mu
is the most undefined value.
Note that most classes do not derive from Mu
directly, but rather from Any.
Methods
method iterator
Defined as:
method iterator(--> Iterator)
Coerces the invocant to a list
by applying its .list
method and uses iterator
on it.
my = Mu.iterator;say .pull-one; # OUTPUT: «(Mu)»say .pull-one; # OUTPUT: «IterationEnd»
method defined
Declared as
multi method defined( --> Bool)
Returns False
on a type object, and True
otherwise.
say Int.defined; # OUTPUT: «False»say 42.defined; # OUTPUT: «True»
A few types (like Failure) override defined
to return False
even for instances:
sub fails() ;say fails().defined; # OUTPUT: «False»
routine defined
Declared as
multi sub defined(Mu --> Bool)
invokes the .defined
method on the object and returns its result.
routine isa
multi method isa(Mu --> Bool)multi method isa(Str --> Bool)
Returns True
if the invocant is an instance of class $type
, a subset type or a derived class (through inheritance) of $type
. does
is similar, but includes roles.
my = 17;say .isa("Int"); # OUTPUT: «True»say .isa(Any); # OUTPUT: «True»;my = 0 but Truish;say .^name; # OUTPUT: «Int+{Truish}»say .does(Truish); # OUTPUT: «True»say .isa(Truish); # OUTPUT: «False»
routine does
method does(Mu --> Bool)
Returns True
if and only if the invocant conforms to type $type
.
my = Date.new('2016-06-03');say .does(Dateish); # True (Date does role Dateish)say .does(Any); # True (Date is a subclass of Any)say .does(DateTime); # False (Date is not a subclass of DateTime)
Unlike isa
, which returns True
only for superclasses, does
includes both superclasses and roles.
say .isa(Dateish); # OUTPUT: «False»
Using the smartmatch operator ~~ is a more idiomatic alternative.
my = Date.new('2016-06-03');say ~~ Dateish; # OUTPUT: «True»say ~~ Any; # OUTPUT: «True»say ~~ DateTime; # OUTPUT: «False»
routine Bool
multi sub Bool(Mu --> Bool)multi method Bool( --> Bool)
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; # OUTPUT: «False»say Mu.new.Bool; # OUTPUT: «True»say [1, 2, 3].Bool; # OUTPUT: «True»say [].Bool; # OUTPUT: «False»say %( hash => 'full' ).Bool; # OUTPUT: «True»say .Bool; # OUTPUT: «False»say "".Bool; # OUTPUT: «False»say 0.Bool; # OUTPUT: «False»say 1.Bool; # OUTPUT: «True»say "0".Bool; # OUTPUT: «True»
method Capture
Declared as:
method Capture(Mu: --> Capture)
Returns a Capture with named arguments corresponding to invocant's public attributes:
.new.Capture.say; # OUTPUT: «\(:bar("something else"), :foo(42))»
method Str
multi method Str(--> 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.my = [2,3,1];say .Str # OUTPUT: «2 3 1»
routine gist
multi sub gist(+args --> Str)multi method gist( --> 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; # OUTPUT: «(Mu)»say Mu.new.gist; # OUTPUT: «Mu.new»
routine perl
multi method perl(--> 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 item
method item(Mu \item:) is raw
Forces the invocant to be evaluated in item context and returns the value of it.
say [1,2,3].item.perl; # OUTPUT: «$[1, 2, 3]»say %( apple => 10 ).item.perl; # OUTPUT: «${:apple(10)}»say "abc".item.perl; # OUTPUT: «"abc"»
method self
method self(--> Mu)
Returns the object it is called on.
method clone
multi method clone(Mu: *)multi method clone(Mu: *)
This method will clone type objects, or die if it's invoked with any argument.
say Num.clone( :yes )# OUTPUT: «(exit code 1) Cannot set attribute values when cloning a type object in block <unit>»
If invoked with value objects, it creates a shallow clone of the invocant, including shallow cloning of private attributes. Alternative values for public attributes can be provided via named arguments with names matching the attributes' names.
my = Point2D.new(x => 2, y => 3);say ; # OUTPUT: «Point(2, 3)»say .clone(y => -5); # OUTPUT: «Point(2, -5)»
Note that .clone
does not go the extra mile to shallow-copy @.
and %.
sigiled attributes and, if modified, the modifications will still be available in the original object:
my = Foo.new;with my = .clone# Hash and Array attribute modifications in clone appear in original as well:say ;# OUTPUT: «Foo.new(foo => 42, bar => ["Z", "Y"], baz => {:X("W"), :Z("Y")}, …»say ;# OUTPUT: «Foo.new(foo => 70, bar => ["Z", "Y"], baz => {:X("W"), :Z("Y")}, …».boo.(); # OUTPUT: «Hi».boo.(); # OUTPUT: «Bye»
To clone those, you could implement your own .clone
that clones the appropriate attributes and passes the new values to Mu.clone
, for example, via nextwith
.
my = Bar.new( :42quux );with my = .clone# Hash and Array attribute modifications in clone do not affect original:say ;# OUTPUT: «Bar.new(quux => 42, foo => ["a", "b"], bar => {:a("b"), :c("d")})»say ;# OUTPUT: «Bar.new(quux => 42, foo => ["Z", "Y"], bar => {:X("W"), :Z("Y")})»
The |%_
is needed to slurp the rest of the attributes that would have been copied via shallow copy.
method new
multi method new(*)multi method new($, *@)
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(* --> Mu)
Low-level object construction method, usually called from within new
, implicitly from the default constructor, or explicitly if you create your own constructor. bless
creates a new object of the same type as the invocant, using the named arguments to initialize attributes and returns the created object.
It is usually invoked within custom new
method implementations:
my = Point.new(-1, 1);
In this case we are declaring new
as a multi method
so that we can still use the default constructor like this: Point.new( x => 3, y => 8 )
. In this case we are declaring this new
method simply to avoid the extra syntax of using pairs when creating the object. self.bless
returns the object, which is in turn returned by new
.
However, in general, implementing a customized new
method might not be the best way of initializing a class, even more so if the default constructor is disabled, since it can make it harder to correctly initialize the class from a subclass. For instance, in the above example, the new
implementation takes two positional arguments that must be passed from the subclass to the superclass in the exact order. That is not a real problem if it's documented, but take into account bless
will eventually be calling BUILD
in the class that is being instantiated. This might result in some unwanted problems, like having to create a BUILD
submethod to serve it correctly:
is Pointmy = Point-with-ID.new(1,2);say .perl;# OUTPUT: «Point-with-ID.new(ID => "*1-2", x => 1, y => 2)»
In this code, bless
, called within Point.new
, is eventually calling BUILD
with the same parameters. We have to create a convoluted way of using the $.ID
attribute using the metaobject protocol so that we can instantiate it and thus serve that new
constructor, which can be called on Point-with-ID
since it is a subclass.
We might have to use something similar if we want to instantiate superclasses. bless
will help us with that, since it is calling across all the hierarchy:
is Strsay Str-with-ID.new("1.1,2e2").ID; # OUTPUT: «0»my = Str-with-ID.new("3,4");say "$enriched-str, , ";# OUTPUT: «3,4, Str-with-ID, 1»
We are enriching Str
with an auto-incrementing ID. We create a new
since we want to initialize it with a string and, besides, we need to instantiate the superclass. We do so using bless
from within new
. bless
is going to call Str.BUILD
. It will *capture* the value it's looking for, the pair value =
$str> and initialize itself. But we have to initialize also the properties of the subclass, which is why within BUILD
we use the previously explained method to initialize $.ID
with the value that is in the %args
variable. As shown in the output, the objects will be correctly initialized with its ID, and will correctly behave as Str
, converting themselves in just the string in the say
statement, and including the ID
property as required.
For more details see the documentation on object construction.
method CREATE
method CREATE(--> Mu)
Allocates a new object of the same type as the invocant, without initializing any attributes.
say Mu.CREATE.defined; # OUTPUT: «True»
method print
multi method print(--> Bool)
Prints value to $*OUT
after stringification using .Str
method without adding a newline at end.
"abc\n".print; # RESULT: «abc»
method put
multi method put(--> Bool)
Prints value to $*OUT
, adding a newline at end, and if necessary, stringifying non-Str
object using the .Str
method.
"abc".put; # RESULT: «abc»
method say
multi method say()
Will say
to standard output.
say 42; # OUTPUT: «42»
What say
actually does is, thus, deferred to the actual subclass. In most cases it calls .gist
on the object, returning a compact string representation.
In non-sink context, say
will always return True
.
say (1,[1,2],"foo",Mu).map: so *.say ;# OUTPUT: «1[1 2]foo(Mu)(True True True True)»
However, this behavior is just conventional and you shouldn't trust it for your code. It's useful, however, to explain certain behaviors.
say
is first printing out in *.say
, but the outermost say
is printing the True
values returned by the so
operation.
method ACCEPTS
multi method ACCEPTS(Mu: )
ACCEPTS
is the method that smartmatching 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; # OUTPUT: «True»say 42 ~~ Int; # OUTPUT: «True»say 42 ~~ Str; # OUTPUT: «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(--> ObjAt)
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; # OUTPUT: «True»
method WHERE
method WHERE(--> Int)
Returns an Int
representing the memory address of the object.
method WHY
multi method WHY(--> Pod::Block::Declarator)
Returns the attached Pod::Block::Declarator.
For instance:
sub cast(Spell )say .WHY;# OUTPUT: «Initiate a specified spell normally(do not use for class 7 spells)»
See Pod declarator blocks for details about attaching Pod to variables, classes, functions, methods, etc.
trait is export
multi sub trait_mod:<is>(Mu \type, :!)
Marks a type as being exported, that is, available to external users.
my 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 ;say f(); # OUTPUT: «any(1, 2, 3)»
method return-rw
Same as method return
except that return-rw
returns a writable container to the invocant (see more details here: return-rw
).
method emit
method emit()
Emits the invocant into the enclosing supply or react block.
react# OUTPUT:# received Str (foo)# received Int (42)# received Rat (0.5)
method take
method take()
Returns the invocant in the enclosing gather block.
sub insert(, +)say insert ':', <a b c>;# OUTPUT: «(a : b : c)»
routine take
sub take(\item)
Takes the given item and passes it to the enclosing gather
block.
my = 6;my = 49;gather for ^.say; # six random values
routine take-rw
sub take-rw(\item)
Returns the given item to the enclosing gather
block, without introducing a new container.
my = 1...3;sub f();for f() ;say ;# OUTPUT: «[2 3 4]»
method so
method so()
Evaluates the item in boolean context (and thus, for instance, collapses Junctions), and returns the result. It is the opposite of not
, and equivalent to the ?
operator.
One can use this method similarly to the English sentence: "If that is so, then do this thing". For instance,
my = <-a -e -b -v>;my = any() eq '-v' | '-V';if .so# OUTPUT: «Verbose option detected in arguments»
The $verbose-selected
variable in this case contains a Junction
, whose value is any(any(False, False), any(False, False), any(False, False), any(True, False))
. That is actually a truish value; thus, negating it will yield False
. The negation of that result will be True
. so
is performing all those operations under the hood.
method not
method not()
Evaluates the item in boolean context (leading to final evaluation of Junctions, for instance), and negates the result. It is the opposite of so
and its behavior is equivalent to the !
operator.
my = <-a -e -b>;my = any() eq '-v' | '-V';if .not# OUTPUT: «Verbose option not present in arguments»
Since there is also a prefix version of not
, this example reads better as:
my = <-a -e -b>;my = any() eq '-v' | '-V';if not# OUTPUT: «Verbose option not present in arguments»