class Signature

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 the code or function in order to call it.

Passing arguments to a signature binds the arguments the parameters, and (loosely speaking) to the signature.

Signature Literals

Signatures appear in parenthesis after subroutine and method names, on blocks after a -> or <-> arrow, as the input to variable declarators like my, or as a separate term starting with a colon.

sub f($x) { }
#    ^^^^ Signature of sub f
method x() { }
#       ^^ Signature of a method
my $s = sub (*@a) { }
#           ^^^^^ Signature of an anonymous function

for @list -> $x { }
#            ^^   Signature of a block

my ($a, @b) = 5, (6,7,8);
#  ^^^^^^^^ Signature of a variable declarator

my $sig = :($a, $b);
#          ^^^^^^^^ Standalone Signature object

Parameter Separators

A signature consists of zero or more parameters, separated by comma.

:($a, @b, %c)
sub add ($a, $b) { $a + $b }

As an exception the first parameter may be followed by a colon instead of a comma to mark the invocant of a method (the invocant is that thing that's bound to self, but by specifying it in the signature, you can change what it's bound to).

:($a: @b, %c)       # first argument is the invocant

class Foo {
    method whoami ($me:) {
        "Well I'm class $me.^name(), of course!"
    }
}
say Foo.whoami; # => Well I'm class Foo, of course!

Type Constraints

Parameters can optionally have a type constraint (the default is Any). These can be used to restrict the allowed input to a function.

:(Int $a, Str $b)

sub divisors (Int $n) { $_ if $n %% $_ for 1..$n }
divisors 2.5; # !!! Calling 'divisors' will never work with argument types (Rat)

Anonymous parameters are fine too, if a parameter is only needed for its type constraint.

:($, @, %a)         # two anonymous and a "normal" parameter
:(Int, Positional)  # just a type is also fine (two parameters)
sub baz (Str) { "Got passed a Str" }

In addition to those nominal types, additional 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 factorial(Int $ where 0) { 1 }
multi factorial(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.

Slurpy (A.K.A. Variadic) Parameters

An array or hash parameter can be marked as slurpy by a leading asterisk, which means it can bind to an arbitrary amount of arguments (zero or more).

These are called "slurpy" because they slurp up any remaining arguments to a function, like someone slurping up noodles.

:($a, @b)           # exactly two arguments, where the second one must be Positional
:($a, *@b)          # at least one argument, where @b is slurpy
:(*%h)              # no positional arguments, but any number of named arguments
sub one-arg (@) { }
sub slurpy (*@) { }
one-arg (5, 6, 7); # ok
slurpy  (5, 6, 7); # ok
one-arg 5, 6, 7; # !!! too many arguments
slurpy  5, 6, 7; # ok
sub named-names (*%named-args) { %named-args.keys }
say named-names :foo(42) :bar<baz> # => foo bar

Note that positional parameters aren't allowed after slurpy parameters.

:(*@args, $last) # !!! Cannot put required parameter after variadic parameters

Positional vs. Named

A parameter can be positional or named. All parameters are positional, except slurpy hash parameters and parameters marked with a leading colon :.

:($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) { "Official business!" if $private }
named :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

Optional and Mandatory Parameters

Positional parameters are mandatory by default, and can be made optional with a default value or a trailing question mark:

:(Str $id)          # required parameter
:($base = 10)       # optional parameter, default value 10
:(Int $x?)          # optional parameter, default is the Int type object

Named parameters are optional by default, and can be made mandatory with a trailing exclamation mark:

:(:%config)         # optional parameter
:(:$debug = False)  # optional parameter, defaults to False
:(:$name!)          # mandatory 'name' named parameter

Default values can depend on previous parameters, and are (at least notionally) computed anew for each call

:($goal, $accuracy = $goal / 100);
:(:$excludes = ['.', '..']);        # a new Array for every call

Destructuring Parameters

Parameters can be followed by a sub-signature in brackets, which will destructure the argument given. The destructuring of a list is just its elements:

    sub first (@array ($first, *@rest)) { $first }

or

    sub first ([$f, *@]) { $f }

While the destructuring of a hash is its pairs:

    sub all-dimensions (% (:length(:$x), :width(:$y), :depth(:$z))) {
        $x andthen $y andthen $z andthen True
    }

In general, an object is destructured based on its attributes. A common idiom is to unpack a Pair's key and value in a for loop:

    for @guest-list.pairs -> (:key($index), :value($guest)) {
        ...
    }

However, this unpacking of objects as their attributes is only the default behavior. To make an object get destructured differently, change its Capture method.

Capture Parameters

Prefixing a parameter with a vertical bar | makes the parameter a Capture, using up all the remaining positional and named arguments.

This is often used in proto definitions (like proto foo (|) {*}) to indicate that the routine's multi definitions can have any type constraints.

Parameter Traits and Modifiers

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 count-up ($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). 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);
}

Methods

method params

method params(Signature:D:) returns Positional

Returns the list of Parameter objects that make up the signature.

method arity

method arity(Signature:D:) returns Int:D

Returns the minimal number of positional arguments required to satisfy the signature.

method count

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.

method returns

Whatever the Signature's return constraint is:

:($a, $b --> Int).returns # Int

method ACCEPTS

multi method ACCEPTS(Signature:D: Capture $topic)
multi method ACCEPTS(Signature:D: @topic)
multi method ACCEPTS(Signature:D: %topic)
multi method ACCEPTS(Signature:D: Signature $topic)

The first three see if the argument could be bound to the capture, i.e., if a function with that Signature would be able to be called with the $topic:

(1,2, :foo) ~~ :($a, $b, :foo($bar))    # True
<a b c d> ~~ :(Int $a)                  # False

The last returns True if anything accepted by $topic would also be accepted by the Signature.

:($a, $b) ~~ :($foo, $bar, $baz?)   # True
:(Int $n) ~~ :(Str)                 # False

Type graph

Below you should see an imgage showing the type relations for Signature. If not, try the PNG version.

perl6-type-graph Signature Signature Any Any Signature->Any Mu Mu Any->Mu

Methods supplied by class Any

Signature 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).

method any

Interprets the invocant as a list and creates an any-Junction from it.

method all

Interprets the invocant as a list and creates an all-Junction from it.

method one

Interprets the invocant as a list and creates an one-Junction from it.

method none

Interprets the invocant as a list and creates an none-Junction from it.

Methods supplied by class Mu

Signature inherits from class Mu, which provides the following methods:

method Str

multi method Str()   returns Str

Returns a string representation of the invocant, intended to be machine readable.

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.

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.

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.

method print

multi method print() returns Bool:D

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

method say

multi method say() returns Bool:D

Prints value to $*OUT after stringification using .gist method with newline at end.

method ACCEPTS

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 { ... }.

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.