class Signature { ... }
A signature is a static description of the parameter list of a code object. That is, it describes what and how many arguments you need to pass to it for invocation.
Passing arguments to a signature binds the arguments the parameters, and (loosely speaking) to the signature.
Signatures appear in parenthesis after subroutine and method names, on blocks after a < - >> or < <- >> arrow, or as a separate term starting with a colon.
sub f($x) { }
# ^^^^ signature
method x() { }
# ^^ signature
my $s = sub (*@a) { }
# ^^^^^ signature
for @list -> $x { }
# ^^ signature
my $sig = :($a, $b); # ^^^^^^^^ signature
A signature consists of zero or more parameters, separated by comma. As an exception the first parameter may be followed by a colon instead of a comma to mark the invocant of a method.
:($a, @b, %c) # comma-separted parameters :($a: @b, %c) # first argument is the invocant
Parameters can optionally have a type constraint (the default is Any). Anonymous parameters are fine too.
:(Int $a, Str $b) # type constraints :($, @, %a) # two anonymous and a "normal" parameter :(Int, Positional) # just a type is also fine (two parameters)
In addition to those nominal types, addtional constraints can be placed on parameters in the form of code blocks which must return a true value to pass the type check
sub f(Real $x where { $x > 0 }, Real $y where { $y >= $x }) { }
In fact it doesn't need to be a code block, anything on the right of the where-block will be used to smart-match the argument against it. So you can also write
multi fact(Int $ where 0) { 1 }
multi fact(Int $x) { $x * fact($x - 1) }
The first of those can be shortened to
multi fact(0) { 1 }
i.e., you can use a literal directly as a type and value constraint on an anonymous parameter.
An array or hash parameter can be marked as slurpy by a leading asterisk, which means they can bind to an arbitrary amount of arguments (zero or more).
:($a, *@b) # at least one argument, @b is slurpy :($a, @b) # two arguments, the second one must be Positional
A parameter can be postional or named. All parameters are positional, except those marked with a leading colon :, and slurpy hash parameters.
:($a) # a positional parameter :(:$a) # a named parameter of name 'a' :(*@a) # a slurpy positional parameter :(*%h) # a slurpy named parameter
On the caller side, positional arguments are passed in the same order as the parameters were declared.
sub pos($x, $y) { "x=$x y=$y" }
pos(4, 5); # x=4 y=5
In the case of named arguments and parameters, only the name is used for mapping arguments to parameters
sub named(:$x, :$y) { "x=$x y=$y" }
named( y => 5, x => 4); # x=4 y=5
It is possible to have a different name for a named parameter than the variable name:
sub named(:official($private) { } # parameter name is 'official'
Aliases are also possible that way:
sub paint( :color(:colour($c)) ) # 'color' and 'colour' are both OK sub paint( :color(:$colour) ) # same API for the caller
Named parameters are optional by default, and can be made mandatory with a trailing exclamation mark:
:(:$name!) # mandatory 'name' named parameter
Positional parameters are mandatory by default, and can be made optional with a default value or a trailing question mark:
:($base = 10) # optional parameter, default value 10 :(Int $x?) # optional parameter, default is the Int type object
Named parameters can also have default values.
Default values can depend on previous parameters, and are (at least notionally) computed anew for each call
:($goal, $accuarcy = $goal / 100); :(:$excludes = ['.', '..']); # a new Array for every call
By default, parameters are bound to their argument and marked as read-only. One can change that with traits on the parameter.
The is copy trait causes the argument to be copied, and allows it to be modified inside the routine
sub c($x is copy) {
$x = Inf if $x ~~ Whatever;
.say for 1..$x;
}
The is rw trait makes the parameter only bind to a variable (or other writable container)[1]. Assigning to the parameter changes the value of the variable at the caller side
sub swap($x is rw, $y is rw) {
($x, $y) = ($y, $x);
}
To bind either to a value or a variable, one can prefix a parameter with a backslash \.
sub f(\$raw) { ... }
Prefixing a parameter with a vertical bar | makes it use up all the remaining positional and named arguments.
method params(Signature:D:) returns Positional
Returns the list of Parameter objects that make up the signature.
method arity(Signature:D:) returns Int:D
Returns the minimal number of positional arguments required to satisfy the signature.
method count(Signature:D:) returns Real:D
Returns the maximal number of positional arguments which can be bound to the signature. Returns Inf if there is a slurpy positional parameter.
Full-size type graph image as SVGSignature inherits from class Any, which provides the following methods:
multi method ACCEPTS(Any:D: Mu $other)
Returns True if $other === self (ie it checks object identity).
Interprets the invocant as a list and creates an any-Junction from it.
Interprets the invocant as a list and creates an all-Junction from it.
Interprets the invocant as a list and creates an one-Junction from it.
Interprets the invocant as a list and creates an none-Junction from it.
Signature inherits from class Mu, which provides the following methods:
multi sub defined(Mu) returns Bool:D multi method defined() returns Bool:D
Returns False on the type object, and True otherwise.
multi sub Bool(Mu) returns Bool:D multi method Bool() returns Bool:D
Returns False on the type object, and True otherwise.
multi method Str() returns Str
Returns a string representation of the invocant, intended to be machine readable.
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, but many built-in classes override it to something more specific.
multi sub perl(Mu) returns Str multi method perl() returns Str
Returns a Perlish representation of the object (i.e., can usually be reparsed to regenerate the object).
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.
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.
method bless(Mu $candidate, *%attrinit) returns Mu:D
Lower-level object construction method than new.
If you pass a Whatever as a candidate, it creates a new object of the same type as the invocant, and then uses the named arguments to initialize attributes.
If you pass something other than a Whatever object as a candidate, it simply does the attribute initialization on the $candidate.
In both cases, the object with the attributes initialized is returned.
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() returns Mu:D
Allocates a new object of the same type as the invocant, without initializating any attributes.
multi method print() returns Bool:D
Prints value to $*OUT after stringification using .Str method without newline at end.
multi method say() returns Bool:D
Prints value to $*OUT after stringification using .gist method with newline at end.
multi method ACCEPTS(Mu:U: $other)
Performs a type check. Returns True if $other conforms to the invocant (which is always a type object or failure).
This is the method that is triggered on smart-matching against type objects, for example in if $var ~~ Int { ... }.
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.