Rules / Types, classes & roles / basic

Mu Reference

The root of the Raku type hierarchy.

What it is #

Position in the hierarchy #

Inherits from
Does
Inherited byJunction, Any

Routines #

Signatures are reproduced from the documentation, including their declared return types. A routine listed here is part of the type's published interface; whether Raku++ implements it is a separate question, answered by the examples below.

method iterator #

method iterator(--> Iterator)

Returns Iterator.

Coerces the invocant to a list by applying its .list method and uses iterator on it.

routine defined #

multi method defined(   --> Bool:D)
multi        defined(Mu --> Bool:D)

Returns Bool:D.

Returns False on a type object, and True otherwise. (The sub evaluates its argument, and the method its invocant.) A few types (like Failure) override defined to return False even for instances:

method isa #

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

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. does is similar, but includes roles.

method does #

method does(Mu $type --> Bool:D)

Returns Bool:D.

Returns True if and only if the invocant conforms to type $type. Unlike isa, which returns True only for superclasses, does includes both superclasses and roles. Using the smartmatch operator ~~ is a more idiomatic alternative.

routine Bool #

multi method Bool(   --> Bool:D)
multi        Bool(Mu --> Bool:D)

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

method Capture #

method Capture(Mu:D: --> Capture:D)

Returns Capture:D.

Returns a Capture with named arguments corresponding to invocant's public attributes:

method Str #

multi method Str(--> 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.

routine gist #

multi method gist(   --> Str)
multi        gist(+args --> Str)

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 .raku to get all elements. The default gist method in Mu re-dispatches to the raku 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

method perl #

multi method perl(Mu:)

Calls .raku on the invocant. Since the change of the language name to Raku, this method is deprecated. Use .raku instead.

method raku #

multi method raku(Mu:U:)
multi method raku(Mu:D:)

For type objects, returns its name if .raku has not been redefined from Mu, or calls .raku on the name of the type object otherwise. For plain objects, it will conventionally return a representation of the object that can be used via EVAL to reconstruct the value of the object.

routine item #

method item(Mu \item:) is raw
multi  item(\x)
multi  item(|c)
multi  item(Mu $a)

Forces the invocant to be evaluated in item context and returns the value of it. You can also use $ as item contextualizer.

method self #

method self(--> Mu)

Returns Mu.

Returns the object it is called on.

method clone #

multi method clone(Mu:U: *%twiddles)
multi method clone(Mu:D: *%twiddles)

This method will clone type objects, or die if it's invoked with any argument. 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. Note that .clone does not go the extra mile to shallow-copy @. and %.

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

method bless #

method bless(*%attrinit --> Mu:D)

Returns Mu:D.

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: In this example we are declaring this new method to avoid the extra syntax

method CREATE #

method CREATE(--> Mu:D)

Returns Mu:D.

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

routine print #

multi method print(--> Bool:D)

Returns Bool:D.

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

routine put #

multi method put(--> Bool:D)

Returns Bool:D.

Prints value to $*OUT, adding a newline at end, and if necessary, stringifying non-Str object using the .Str method.

routine say #

multi method say()

Will say to standard output. 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. However, this behavior is just conventional and you shouldn't trust it for

method ACCEPTS #

multi method ACCEPTS(Mu:U: $other)

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). Note that there is no multi for defined invocants; this is to allow autothreading of junctions, which happens as a fallback

method WHICH #

multi method WHICH(--> ObjAt:D)

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.

method WHERE #

method WHERE(Mu:)

Returns an Int representing the memory address of the object. Please note that in the Rakudo implementation of Raku, and possibly other implementations, the memory location of an object is NOT fixed for the lifetime of the object. So it has limited use for applications, and is intended as a debugging tool only.

method WHY #

multi method WHY(Mu: --> Pod::Block::Declarator)

Returns Pod::Block::Declarator.

Returns the attached Pod::Block::Declarator. For instance: See Pod declarator blocks for details about attaching Pod to variables, classes, functions, methods, etc.

trait is #

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

Marks a type as being exported, that is, available to external users. 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.

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

routine return-rw #

Same as routine return except that return-rw returns a writable container to the invocant (see more details here: return-rw).

routine emit #

method emit()

Emits the invocant into the enclosing supply or react block.

routine take #

method take()
sub    take(\item)

The sub takes the given item and passes it to the enclosing gather block. The method returns the invocant in the enclosing gather block.

sub take-rw #

sub take-rw(\item)

Returns the given item to the enclosing gather block, without introducing a new container.

routine 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, The $verbose-selected variable in this case contains a Junction, whose value is C<any(any(False, False),

routine 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. Since there is also a prefix version of not, this example reads better as:

Examples, run three ways #

Every example below comes from the official documentation, together with the output that documentation asserts. Each was then executed by Rakudo and by Raku++ when this page was built. Where the three agree, one result is shown; where they do not, all three are — because which of them is wrong is exactly the information worth having.

2 all-differ · 1 doc-drift · 7 no-output · 1 not-runnable · 25 ok · 1 rakudo-differs · 3 rakupp-differs

class Mu { }

Not executed: the documentation states no expected output for this example.

my $it = Mu.iterator;
say $it.pull-one; # OUTPUT: «(Mu)␤»
say $it.pull-one; # OUTPUT: «IterationEnd␤»
Output
(Mu)
IterationEnd

Documentation, Rakudo and Raku++ all agree.

say Int.defined;                # OUTPUT: «False␤»
say 42.defined;                 # OUTPUT: «True␤»
Output
False
True

Documentation, Rakudo and Raku++ all agree.

sub fails() { fail 'oh noe' };
say fails().defined;            # OUTPUT: «False␤»
Output
False

Documentation, Rakudo and Raku++ all agree.

my $i = 17;
say $i.isa("Int");   # OUTPUT: «True␤»
say $i.isa(Any);     # OUTPUT: «True␤»
role Truish {};
my $but-true = 0 but Truish;
say $but-true.^name;        # OUTPUT: «Int+{Truish}␤»
say $but-true.does(Truish); # OUTPUT: «True␤»
say $but-true.isa(Truish);  # OUTPUT: «False␤»
Output
True
True
Int+{Truish}
True
False

Documentation, Rakudo and Raku++ all agree.

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

Documentation, Rakudo and Raku++ all agree.

say $d.isa(Dateish); # OUTPUT: «False␤»
Output
False

Documentation, Rakudo and Raku++ all agree.

my $d = Date.new('2016-06-03');
say $d ~~ Dateish;                # OUTPUT: «True␤»
say $d ~~ Any;                    # OUTPUT: «True␤»
say $d ~~ DateTime;               # OUTPUT: «False␤»
Output
True
True
False

Documentation, Rakudo and Raku++ all agree.

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␤»
Output
False
True
True
False
True
False
False
False
True
True

Documentation, Rakudo and Raku++ all agree.

class Foo {
    has $.foo = 42;
    has $.bar = 70;
    method bar { 'something else' }
}.new.Capture.say; # OUTPUT: «\(:bar("something else"), :foo(42))␤»
Output
\(:bar("something else"), :foo(42))

Documentation, Rakudo and Raku++ all agree.

say Mu.Str;   # Use of uninitialized value of type Mu in string context.
my @foo = [2,3,1];
say @foo.Str  # OUTPUT: «2 3 1␤»
Documentation
2 3 1
Rakudo

2 3 1
Raku++

2 3 1

Both engines agree; the documentation states something else. Trust the engines.

say Mu.gist;        # OUTPUT: «(Mu)␤»
say Mu.new.gist;    # OUTPUT: «Mu.new␤»
Output
(Mu)
Mu.new

Documentation, Rakudo and Raku++ all agree.

say Str.raku;          # OUTPUT: «Str␤»
Output
Str

Documentation, Rakudo and Raku++ all agree.

say (1..3).Set.raku;  # OUTPUT: «Set.new(1,2,3)␤»
Documentation
Set.new(1,2,3)
Rakudo
Set.new(3,2,1)
Raku++
Set.new(1,2,3)

Raku++ matches the documentation; Rakudo does not. This is the one class where neither engine can be assumed right: it may be a stale doc that Raku++ was built from, or it may be a Rakudo bug that the documentation predates. Each case is examined individually.

Not yet examined. Which of these is correct has not been established — do not treat either engine as settled here.

say [1,2,3].item.raku;          # OUTPUT: «$[1, 2, 3]␤»
say %( apple => 10 ).item.raku; # OUTPUT: «${:apple(10)}␤»
say item([1,2,3]).raku;         # OUTPUT: «$[1, 2, 3]␤»
say item("abc").raku;           # OUTPUT: «"abc"␤»
Output
$[1, 2, 3]
${:apple(10)}
$[1, 2, 3]
"abc"

Documentation, Rakudo and Raku++ all agree.

say $[1,2,3].raku;              # OUTPUT: «$[1, 2, 3]␤»
say $("abc").raku;              # OUTPUT: «"abc"␤»
Output
$[1, 2, 3]
"abc"

Documentation, Rakudo and Raku++ all agree.

say Num.clone( :yes )
# OUTPUT: «(exit code 1) Cannot set attribute values when cloning a type object␤  in block <unit>␤␤»
Documentation
(exit code 1) Cannot set attribute values when cloning a type object
  in block <unit>

Rakudo
Raku++
(Num)

All three differ. Needs a human.

Not yet examined. Which of these is correct has not been established — do not treat either engine as settled here.

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

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

say $p;                     # OUTPUT: «Point(2, 3)␤»
say $p.clone(y => -5);      # OUTPUT: «Point(2, -5)␤»
Output
Point(2, 3)
Point(2, -5)

Documentation, Rakudo and Raku++ all agree.

class Foo {
has $.foo is rw = 42;
has &.boo is rw = { say "Hi" };
has @.bar       = <a b>;
has %.baz       = <a b c d>;
}

my $o1 = Foo.new;
with my $o2 = $o1.clone {
.foo = 70;
.bar = <Z Y>;
.baz = <Z Y X W>;
.boo = { say "Bye" };
}

# Hash and Array attribute modifications in clone appear in original as well:
say $o1;
# OUTPUT: «Foo.new(foo => 42, bar => ["Z", "Y"], baz => {:X("W"), :Z("Y")}, …␤»
say $o2;
# OUTPUT: «Foo.new(foo => 70, bar => ["Z", "Y"], baz => {:X("W"), :Z("Y")}, …␤»
$o1.boo.(); # OUTPUT: «Hi␤»
$o2.boo.(); # OUTPUT: «Bye␤»
Documentation
Foo.new(foo => 42, bar => ["Z", "Y"], baz => {:X("W"), :Z("Y")}, …
Foo.new(foo => 70, bar => ["Z", "Y"], baz => {:X("W"), :Z("Y")}, …
Hi
Bye
Rakudo
Foo.new(foo => 42, boo => -> ;; $_? is raw = OUTER::<$_> { #`(Block|5402470186224) ... }, bar => ["Z", "Y"], baz => {:X("W"), :Z("Y")})
Foo.new(foo => 70, boo => -> ;; $_? is raw = OUTER::<$_> { #`(Block|5402470189032) ... }, bar => ["Z", "Y"], baz => {:X("W"), :Z("Y")})
Hi
Bye
Raku++
Foo.new(foo => 42, boo => sub { ... }, bar => ["a", "b"], baz => {})
Foo.new(foo => 70, boo => sub { ... }, bar => $("Z", "Y"), baz => $("Z", "Y", "X", "W"))
Hi
Bye

All three differ. Needs a human.

Not yet examined. Which of these is correct has not been established — do not treat either engine as settled here.

class Bar {
has $.quux;
has @.foo = <a b>;
has %.bar = <a b c d>;
method clone { nextwith :foo(@!foo.clone), :bar(%!bar.clone), |%_  }
}

my $o1 = Bar.new( :42quux );
with my $o2 = $o1.clone {
.foo = <Z Y>;
.bar = <Z Y X W>;
}

# Hash and Array attribute modifications in clone do not affect original:
say $o1;
# OUTPUT: «Bar.new(quux => 42, foo => ["a", "b"], bar => {:a("b"), :c("d")})␤»
say $o2;
# OUTPUT: «Bar.new(quux => 42, foo => ["Z", "Y"], bar => {:X("W"), :Z("Y")})␤»
Documentation
Bar.new(quux => 42, foo => ["a", "b"], bar => {:a("b"), :c("d")})
Bar.new(quux => 42, foo => ["Z", "Y"], bar => {:X("W"), :Z("Y")})
Rakudo
Bar.new(quux => 42, foo => ["a", "b"], bar => {:a("b"), :c("d")})
Bar.new(quux => 42, foo => ["Z", "Y"], bar => {:X("W"), :Z("Y")})
Raku++

Raku++ disagrees with both the documentation and Rakudo — a defect.

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

Not executed: the documentation states no expected output for this example.

say Mu.CREATE.defined;  # OUTPUT: «True␤»
Output
True

Documentation, Rakudo and Raku++ all agree.

"abc\n".print;          # OUTPUT: «abc␤»
Output
abc

Documentation, Rakudo and Raku++ all agree.

"abc".put;              # OUTPUT: «abc␤»
Output
abc

Documentation, Rakudo and Raku++ all agree.

say 42;                 # OUTPUT: «42␤»
Output
42

Documentation, Rakudo and Raku++ all agree.

say (1,[1,2],"foo",Mu).map: so *.say ;
# OUTPUT: «1␤[1 2]␤foo␤(Mu)␤(True True True True)␤»
Output
1
[1 2]
foo
(Mu)
(True True True True)

Documentation, Rakudo and Raku++ all agree.

say 42 ~~ Mu;           # OUTPUT: «True␤»
say 42 ~~ Int;          # OUTPUT: «True␤»
say 42 ~~ Str;          # OUTPUT: «False␤»
Output
True
True
False

Documentation, Rakudo and Raku++ all agree.

say 42.WHICH eq 42.WHICH;       # OUTPUT: «True␤»
Output
True

Documentation, Rakudo and Raku++ all agree.

#| Initiate a specified spell normally
sub cast(Spell $s) {
  do-raw-magic($s);
}
#= (do not use for class 7 spells)
say &cast.WHY;
# OUTPUT: «Initiate a specified spell normally␤(do not use for class 7 spells)␤»
Documentation
Initiate a specified spell normally
(do not use for class 7 spells)
Rakudo
Initiate a specified spell normally
(do not use for class 7 spells)
Raku++
Initiate a specified spell normally

Raku++ disagrees with both the documentation and Rakudo — a defect.

my class SomeClass is export { }

Not executed: the documentation states no expected output for this example.

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

Documentation, Rakudo and Raku++ all agree.

react { whenever supply { .emit for "foo", 42, .5 } {
    say "received {.^name} ($_)";
}}

Not executed: the documentation states no expected output for this example.

# OUTPUT:
# received Str (foo)
# received Int (42)
# received Rat (0.5)

Not executed: the documentation states no expected output for this example.

#| 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;    # six random values

Not executed: the documentation states no expected output for this example.

sub insert($sep, +@list) {
    gather for @list {
        FIRST .take, next;
        take slip $sep, .item
    }
}

Not executed: the documentation states no expected output for this example.

say insert ':', <a b c>;
# OUTPUT: «(a : b : c)␤»

Neither engine can run this in isolation — the example depends on context from the surrounding text.

my @a = 1...3;
sub f(@list){ gather for @list { take-rw $_ } };
for f(@a) { $_++ };
say @a;
# OUTPUT: «[2 3 4]␤»
Documentation
[2 3 4]
Rakudo
[2 3 4]
Raku++

Raku++ disagrees with both the documentation and Rakudo — a defect.

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

Documentation, Rakudo and Raku++ all agree.

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

Documentation, Rakudo and Raku++ all agree.

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

Documentation, Rakudo and Raku++ all agree.