class Whatever

Placeholder for unspecified value/parameter

class Whatever { }

Whatever is a class whose objects don't really do much; it gets its semantic from other routines that accept Whatever-objects as markers to do something special. The * literal in term position creates a Whatever object.

Another source of speciality is that the compiler turns combinations of * in term position and many operators into closures. This process is called Whatever-currying.

my $c = * + 2;          # same as   -> $x { $x + 2 };
say $c(4);              # 6

Multiple * in one expression generate closures with as many arguments:

my $c = * + *;          # same as   -> $x, $y { $x + $y }

* in complex expressions also generate closures:

my $c = 4 * * + 5;      # same as   -> $x { 4 * $x + 5 }

Calling a method on * also create a closure:

say <a b c>.map: *.uc;  # A B C

Those closure are of type WhateverCode.

Not all operators and syntactic constructs curry Whatever-stars.

Exception Example What it does
comma 1, *, 2 generates a Parcel with a * element
range operators 1..* Range.new(:from(1), :to(*));
series operator 1 ... * infinite list
smart-matching 1 ~~ * returns True
assignment $x = * assign * to $x
binding $x := * binds * to $x
list repetition 1 xx * generates infinite list

The range operators are handled specially. They do not curry with Whatever-stars, but they do curry with WhateverCode

say (1..*).WHAT;        # Range
say (1..*-1).WHAT;      # WhateverCode

This allow all these constructs to work:

.say for 1..*;          # infinite loop
my @a = 1..4;
say @a[1..*];           # 2 3 4
say @a[1..*-2];         # 2 3

The currying is purely syntactic.

my $x = *;
$x + 2;                 # not a closure, dies because
                        # it can't coerce $x to Numeric

Methods

method ACCEPTS

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

Returns True.

Type graph

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

perl6-type-graph Whatever Whatever Any Any Whatever->Any Mu Mu Any->Mu

Routines supplied by class Any

Whatever 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

Whatever 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