class Signature

Parameter list pattern

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, contained in a Capture, to the signature.

Signature Literals

Signatures appear inside parentheses 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 
my method x() { }
#          ^^ Signature of a method 
my $s = sub (*@a{ }
#           ^^^^^ Signature of an anonymous function 
 
for <a b c> -> $x { }
#              ^^   Signature of a Block 
 
my ($a@b= 5, (678);
#  ^^^^^^^^ Signature of a variable declarator 
 
my $sig = :($a$b);
#          ^^^^^^^^ Standalone Signature object 

Signature literals can be used to define the signature of a callback or a closure.

sub f(&c:(Int)) { }
sub will-work(Int{ }
sub won't-work(Str{ }
f(&will-work);
 
f(&won't-work);
CATCH { default { put .^name''.Str } };
# OUTPUT: «X::TypeCheck::Binding::Parameter: Constraint type check failed in binding to parameter '&c'␤» 
 
f(-> Int { 'this works too' } );

Smart matching signatures against a List is supported.

my $sig = :(Int $iStr $s);
say (10'answer'~~ $sig;
# OUTPUT: «True␤» 
given ('answer'10{
    when :(StrInt{ say 'match' }
    when $sig { say 'mismatch' }
}
# OUTPUT: «match␤» 

When smart matching against a Hash, the signature is assumed to consist of the keys of the Hash.

my %h = left => 1right => 2;
say %h ~~ :(:$left:$right);
# OUTPUT: «True␤» 

Parameter Separators

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

my $sig = :($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 the object that was used to call the method, which is usually bound to self. By specifying it in the signature, you can change the variable name it is bound to.

method ($a: @b%c{};       # first argument is the invocant 
 
class Foo {
    method whoami($me:{
        "Well I'm class $me.^name(), of course!"
    }
}
say Foo.whoami# OUTPUT: «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.

my $sig = :(Int $aStr $b);
sub divisors(Int $n{ $_ if $n %% $_ for 1..$n };
divisors 2.5;
# ===SORRY!=== Error while compiling: 
# Calling divisors(Rat) will never work with declared signature (Int $n) 

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

my $sig = :($@%a);              # two anonymous and a "normal" parameter 
$sig = :(IntPositional);          # just a type is also fine (two parameters) 
sub baz(Str{ "Got passed a Str" }

Type constraints may also be type captures.

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-clause 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 * factorial($x - 1}

The first of those can be shortened to

multi factorial(0{ 1 }

i.e., you can use a literal directly as a type and value constraint on an anonymous parameter.

Tip: pay attention to not accidentally leave off a block when you, say, have several conditions:

-> $y where   .so && .name    {}sub one   {} ); # WRONG!! 
-> $y where { .so && .name }  {}sub two   {} ); # OK! 
-> $y where   .so &  .name.so {}sub three {} ); # Also good 

The first version is wrong and will issue a warning about sub object coerced to string. The reason is the expression is equivalent to ($y ~~ ($y.so && $y.name)); that is "call .so, and if that is True, call .name; if that is also True use its value for smartmatching…". It's the result of (.so && .name) is will be smart-matched against, but we want to check that both .so and .name are truthy values. That is why an explicit Block or a Junction is the right version.

All previous arguments that are not part of a sub-signature in a Signature are accessible in a where-clause that follows an argument. Therefore, the where-clause of the last argument has access to all arguments of a signature that are not part of a sub-signature. For a sub-signature place the where-clause inside the sub-signature.

sub one-of-them(:$a:$b:$c where { $a.defined ^^ $b.defined ^^ $c.defined }{
    $a // $b // $c
};
say one-of-them(c=>42); # OUTPUT: «42␤» 

Note: where-clauses that produce side-effects (e.g. printing output, pulling from an iterator, or increasing a state variable) are not supported and may produce surprising results if used.

Constraining Optional Arguments

Optional arguments can have constraints, too. Any where clause on any parameter will be executed, even if it's optional and not provided by the caller. In that case you may have to guard against undefined values within the where clause.

sub f(Int $aUInt $i? where { !$i.defined or $i > 5 } ) { ... }

Constraining Slurpy Arguments

Slurpy arguments can not have type constraints. A where-clause in conjunction with a Junction can be used to that effect.

sub f(*@a where {$_.all ~~ Int}{ say @a };
f(42);
f(<a>);
CATCH { default { say .^name' ==> '.Str }  }
# OUTPUT: «[42]␤Constraint type check failed in binding to parameter '@a' ...» 

Constraining named Arguments

Constraints against Named arguments apply to the value part of the colon-pair.

sub f(Int :$i){};
f :i<forty-two>;
CATCH { default { say .^name' ==> '.Str }  }
# OUTPUT: «X::TypeCheck::Binding::Parameter ==> Type check failed in binding to parameter '$i'; expected Int but got Str ("forty-two")␤» 

Constraining Defined and Undefined Values

Normally, a type constraint only checks whether the value passed is of the correct type.

sub limit-lines(Str $sInt $limit{
    my @lines = $s.lines;
    @lines[0 .. min @lines.elems$limit].join("\n")
}
say (limit-lines "\n b \n c \n d \n"3).perl# "a \n b \n c \n d " 
say limit-lines Str3;
CATCH { default { put .^name''.Str } };
# OUTPUT: «X::Multi::NoMatch: Cannot resolve caller lines(Str: ); none of these signatures match: 
#     (Str:D $: :$count!, *%_) 
#     (Str:D $: $limit, *%_) 
#     (Str:D $: *%_)» 
say limit-lines "\n b"Int # Always returns the max number of lines 

In this case, we really only want to deal with defined strings. To do this, we use the :D type constraint.

sub limit-lines(Str:D $sInt $limit{ };
say limit-lines Str3;
CATCH { default { put .^name ~ '--' ~~ .Str } };
# OUTPUT: «Parameter '$s' of routine 'limit-lines' must be an object instance of type 'Str', 
#          not a type object of type 'Str'.  Did you forget a '.new'?» 

This is much better than the way the program failed before, since here the reason for failure is clearer.

It's also possible undefined types are the only ones that make sense for a routine to accept. This can be constrained with the :U type constraint. For example, we can turn the &limit-lines into a multi function to make use of the :U constraint.

multi limit-lines(Str $sInt:D $limit{ }
multi limit-lines(Str $sInt:U $) { $s }
say limit-lines "\n b \n c"Int# OUTPUT: «"a \n b \n c"␤» 

For explicitly indicating the normal behaviour, :_ can be used, but this is unnecessary. :(Num:_ $) is the same as :(Num $).

Constraining signatures of Callables

To constrain block and subroutine references based on their signature write the signature after the argument name.

sub f(&c:(IntStr))  { say c(10'ten'};
sub g(Int $iStr $s{ $s ~ $i };
f(&g);
# OUTPUT: «ten10␤» 

Constraining Return Types

There are multiple ways to constrain return types on a sub or method. All versions below are currently valid and will force a type check on successful execution of a routine.

Nil and Failure are always allowed as return types, regardless of any type constraint. This allows Failure to be returned and passed on down the call chain.

sub foo(--> Int{ Nil };
say foo.perl# OUTPUT: «Nil␤» 

Type captures are not supported.

This form is preferred for several reasons: (1) it can handle constant values while the others can't; (2) for consistency, it is the only form accepted on this site;

The return type arrow has to be placed at the end of the parameter list, with or without a , before it.

sub greeting1(Str $name  --> Str{ say "Hello, $name" } # Valid 
sub greeting2(Str $name--> Str{ say "Hello, $name" } # Valid 
 
sub favorite-number1(--> 42{        } # OUTPUT: 42 
sub favorite-number2(--> 42{ return } # OUTPUT: 42 

If the type constraint is a constant expression, it is used as the return value of the routine. Any return statement in that routine has to be argumentless.

sub foo(Str $word --> 123{ say $wordreturn}
my $value = foo("hello"); # OUTPUT: hello 
say $value;               # OUTPUT: 123 
# The code below will not compile 
sub foo(Str $word --> 123{ say $wordreturn $word}
my $value = foo("hello");
say $value;

The keyword returns following a signature declaration has the same function as --> with two caveats.

(1) This form is planned for future removal. (2) This form does not work with constant values

    sub greeting(Str $namereturns Str { say "Hello, $name" } # Valid 
    sub favorite-number returns 42 {        } # This will fail. 

of is just the real name of the returns keyword.

    sub foo() of Int { 42 }# Valid 
    sub foo() of 42 {  };    # This will fail. 

This is similar to placing type constraints on variables like my Type $var = 20;, except the $var is a definition for a routine.

    my Int sub bar { 1 };     # Valid 
    my 42 sub bad-answer {};  # This will fail. 

Coercion Type

To accept one type but coerce it automatically to another, use the accepted type as an argument to the target type. If the accepted type is Any it can be omitted.

sub f(Int(Str$want-intStr() $want-str{
    say $want-int.^name ~ ' ' ~ $want-str.^name
}
f '10'10;
# OUTPUT: «Int Str␤» 
 
use MONKEY;
augment class Str { method Date() { Date.new(self} };
sub foo(Date(Str$d{ say $d.^namesay $d };
foo "2016-12-01";
# OUTPUT: «Date␤2016-12-01␤» 

Slurpy (A.K.A. Variadic) Parameters

A function is variadic if it can take a varying number of arguments; that is, its arity is not fixed. Therefore, optional, named, and slurpy parameters are variadic. An array or hash parameter can be marked as slurpy by leading asterisk (*) or two leading asterisks (**) or a leading plus (+). A slurpy parameter can bind to an arbitrary number 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, @b slurps up any beyond that 
$ = :(*%h);        # no positional arguments, but any number of named arguments 
 
sub one-arg (@)  { }
sub slurpy  (*@) { }
one-arg (567); # ok, same as one-arg((5, 6, 7)) 
slurpy  (567); # ok 
slurpy   567 ; # ok 
# one-arg(5, 6, 7) ; # X::TypeCheck::Argument 
# one-arg  5, 6, 7 ; # X::TypeCheck::Argument 
 
sub named-names (*%named-args{ %named-args.keys };
say named-names :foo(42:bar<baz># OUTPUT: «foo bar␤» 

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

:(*@args$last);
# ===SORRY!=== Error while compiling: 
# Cannot put required parameter $last after variadic parameters 

Normally a slurpy parameter will create an Array, create a new Scalar container for each argument, and assign the value from each argument to those Scalars. If the original argument also had an intermediary Scalar it is bypassed during this process, and is not available inside the called function.

Slurpy parameters have special behaviors when combined with some traits and modifiers, as described below.

Types of Slurpy Array Parameters

There are three variations to slurpy array parameters.

Each will be described in detail in the next few sections. As the difference between each is a bit nuanced, examples are provided for each to demonstrate how each slurpy convention varies from the others.

Flattened Slurpy

Slurpy parameters declared with one asterisk will flatten arguments by dissolving one or more layers of bare Iterables.

my @array = <a b c>;
my $list := <d e f>;
sub a(*@a)  { @a.perl.say };
a(@array);                 # OUTPUT: «["a", "b", "c"]» 
a(1$list, [23]);       # OUTPUT: «[1, "d", "e", "f", 2, 3]» 
a([12]);                 # OUTPUT: «[1, 2]» 
a(1, [12], ([34], 5)); # OUTPUT: «[1, 1, 2, 3, 4 5]» 
a(($_ for 123));       # OUTPUT: «[1, 2, 3]» 

A single asterisk slurpy flattens all given iterables, effectively hoisting any object created with commas up to the top level.

Unflattened Slurpy

Slurpy parameters declared with two stars do not flatten any iterable arguments within the list, but keep the arguments more or less as-is:

my @array = <a b c>;
my $list := <d e f>;
sub b(**@b{ @b.perl.say };
b(@array);                 # OUTPUT: «[["a", "b", "c"],]␤» 
b(1$list, [23]);       # OUTPUT: «[1, ("d", "e", "f"), [2, 3]]␤» 
b([12]);                 # OUTPUT: «[[1, 2],]␤» 
b(1, [12], ([34], 5)); # OUTPUT: «[1, [1, 2], ([3, 4], 5)]␤» 
b(($_ for 123));       # OUTPUT: «[(1, 2, 3),]␤» 

The double asterisk slurpy hides the nested comma objects and leaves them as-is in the slurpy array.

Single Argument Rule Slurpy

A slurpy parameter created using a plus engages the "single argument rule", which decides how to handle the slurpy argument based upon context. Basically, if only a single argument is passed and that argument is iterable, that argument is used to fill the slurpy parameter array. In any other case, +@ works like **@.

my @array = <a b c>;
my $list := <d e f>;
sub c(+@b{ @b.perl.say };
c(@array);                 # OUTPUT: «["a", "b", "c"]␤» 
c(1$list, [23]);       # OUTPUT: «[1, ("d", "e", "f"), [2, 3]]␤» 
c([12]);                 # OUTPUT: «[1, 2]␤» 
c(1, [12], ([34], 5)); # OUTPUT: «[1, [1, 2], ([3, 4], 5)]␤» 
c(($_ for 123));       # OUTPUT: «[1, 2, 3]␤» 

For additional discussion and examples, see Slurpy Conventions for Functions.

Type Captures

Type Captures allow deferring the specification of a type constraint to the time the function is called. They allow referring to a type both in the signature and the function body.

sub f(::T $p1T $p2, ::C){
    # $p1 and $p2 are of the same type T, that we don't know yet 
    # C will hold a type we derive from a type object or value 
    my C $closure = $p1 / $p2;
    return sub (T $p1{
        $closure * $p1;
    }
}
 
# The first parameter is Int and so must be the 2nd. 
# We derive the 3rd type from calling the operator that is used in &f. 
my &s = f(102Int.new / Int.new);
say s(2)# 10 / 2 * 2 == 10 

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 :. The latter is called a colon-pair.

$ = :($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(45);                          # RESULT: «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=> 5x => 4);             # RESULT: «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 ( :color(:colour($c)) ) { }    # 'color' and 'colour' are both OK 
sub ( :color(:$colour) ) { }       # same API for the caller 

A function with named arguments can be called dynamically, dereferencing a Pair with | to turn it into a named argument.

multi f(:$named{ note &?ROUTINE.signature };
multi f(:$also-named{ note &?ROUTINE.signature };
for 'named''also-named' -> $n {
    f(|($n => rand))                    # OUTPUT: «(:$named)␤(:$also-named)␤» 
}
 
my $pair = :named(1);
f |$pair;                               # OUTPUT: «(:$named)␤» 

The same can be used to convert a Hash into named arguments.

sub f(:$also-named{ note &?ROUTINE.signature };
my %pairs = also-named => 4;
f |%pairs;                              # OUTPUT: «(:$also-named)␤» 

A Hash that contains a list may prove problematic when slipped into named arguments. To avoid the extra layer of containers coerce to Map before slipping.

class C { has $.xhas $.yhas @.z };
my %h = <x y z> Z=> (520, [1,2]);
say C.new(|%h.Map);
# OUTPUT: «C.new(x => 5, y => 20, z => [1, 2])␤» 

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 

Dynamic Variables

Dynamic variables are allowed in signatures although they don't provide special behaviour because argument binding does connect two scopes anyway.

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 <Peter Paul Merry>.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.

Sub-signatures

To match against a compound parameter use a sub-signature following the argument name in parentheses.

sub foo(|c(IntStr)){
   put "called with {c.perl}"
};
foo(42"answer");
# OUTPUT: «called with \(42, "answer")␤» 

Long Names

To exclude certain parameters from being considered in multiple dispatch, separate them with a double semi-colon.

multi sub f(Int $iStr $s;; :$b{ dd $i$s$b };
f(10'answer');
# OUTPUT: «10␤"answer"␤Any $b = Any␤» 

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. See proto for an example.

If bound to a variable arguments can be forwarded as a whole using the slip operator |.

sub a(Int $iStr $s{ say $i.^name ~ ' ' ~ $s.^name }
sub b(|c{ say c.^namea(|c}
b(42"answer");
# OUTPUT: «Capture␤Int Str␤» 

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 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);
}

On slurpy parameters, is rw is reserved for future use by language designers.

The is raw trait is automatically applied to parameters declared with a backslash as a "sigil", and may also be used to make normally sigiled parameters behave like these do. In the special case of slurpies, which normally produce an Array full of Scalars as described above, is raw will instead cause the parameter to produce a List. Each element of that list will be bound directly as raw parameter.

To explicitly ask for a read-only parameter use the is readonly trait. Please note that this applies only to the container. The object inside can very well have mutator methods and Perl 6 will not enforce immutability on the attributes of the object.

Traits can be followed by the where clause:

sub ip-expand-ipv6($ip is copy where m:i/^<[a..f\d\:]>**3..39$/{ }

Methods

method params

method params(Signature:D: --> Positional)

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

method arity

method arity(Signature:D: --> Int:D)

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

method count

method count(Signature:D: --> 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 # RESULT: «(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:

(12:foo~~ :($a$b:foo($bar));   # RESULT: «True» 
<a b c d> ~~ :(Int $a);                  # RESULT: «False» 

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

:($a$b~~ :($foo$bar$baz?);   # RESULT: «True» 
:(Int $n~~ :(Str);                 # RESULT: «False» 

Type graph

Type relations for Signature
perl6-type-graph Signature Signature Any Any Signature->Any Mu Mu Any->Mu

Stand-alone image: vector

Routines supplied by class Any

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

(Any) method ACCEPTS

Defined as:

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

Usage:

EXPR.ACCEPTS(EXPR);

Returns True if $other === self (i.e. it checks object identity).

Many built-in types override this for more specific comparisons

(Any) method any

Defined as:

method any(--> Junction:D)

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

say so 2 == <1 2 3>.any;        # OUTPUT: «True␤» 
say so 5 == <1 2 3>.any;        # OUTPUT: «False␤» 

(Any) method all

Defined as:

method all(--> Junction:D)

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

say so 1 < <2 3 4>.all;         # OUTPUT: «True␤» 
say so 3 < <2 3 4>.all;         # OUTPUT: «False␤» 

(Any) method one

Defined as:

method one(--> Junction:D)

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

say so 1 == (123).one;      # OUTPUT: «True␤» 
say so 1 == (121).one;      # OUTPUT: «False␤» 

(Any) method none

Defined as:

method none(--> Junction:D)

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

say so 1 == (123).none;     # OUTPUT: «False␤» 
say so 4 == (123).none;     # OUTPUT: «True␤» 

(Any) method list

Defined as:

method list(--> List:D)

Interprets the invocant as a list, and returns that List.

say 42.list.^name;           # OUTPUT: «List␤» 
say 42.list.elems;           # OUTPUT: «1␤» 

(Any) method push

Defined as:

method push(|values --> Positional:D)

The method push is defined for undefined invocants and allows for autovivifying undefined to an empty Array, unless the undefined value implements Positional already. The argument provided will then be pushed into the newly created Array.

my %h;
dd %h<a>;      # Any (and therefore undefined) 
%h<a>.push(1); # .push on Any 
dd %h;         # «Hash %h = {:a($[1])}␤» # please note the Array 

(Any) routine reverse

Defined as:

multi sub    reverse(*@list  --> Seq:D)
multi method reverse(List:D: --> Seq:D)

Returns a Seq with the same elements in reverse order.

Note that reverse always refers to reversing elements of a list; to reverse the characters in a string, use flip.

Examples:

say <hello world!>.reverse;     # OUTPUT: «(world! hello)␤» 
say reverse ^10;                # OUTPUT: «(9 8 7 6 5 4 3 2 1 0)␤» 

(Any) method sort

Defined as:

multi method sort()
multi method sort(&custom-routine-to-use)

Sorts iterables with infix:<cmp> or given code object and returns a new List. Optionally, takes a Callable as a positional parameter, specifying how to sort.

Examples:

say <b c a>.sort;                           # OUTPUT: «(a b c)␤» 
say 'bca'.comb.sort.join;                   # OUTPUT: «abc␤» 
say 'bca'.comb.sort({$^b cmp $^a}).join;    # OUTPUT: «cba␤» 
say '231'.comb.sort(&infix:«<=>»).join;     # OUTPUT: «123␤» 

(Any) method map

Defined as:

multi method map(\SELF: &block;; :$label:$item)
multi method map(HyperIterable:D: &block;; :$label)

map will iterate over the invocant and apply the number of positional parameters of the code object from the invocant per call. The returned values of the code object will become elements of the returned Seq.

The :$label and :$item are useful only internally, since for loops get converted to maps. The :$label takes an existing Label to label the .map's loop with and :$item controls whether the iteration will occur over (SELF,) (if :$item is set) or SELF.

(Any) method deepmap

Defined as:

method deepmap(&block --> Listis nodal

deepmap will apply &block to each element and return a new List with the return values of &block, unless the element does the Iterable role. For those elements deepmap will descend recursively into the sublist.

dd [[1,2,3],[[4,5],6,7]].deepmap(*+1);
# OUTPUT: «[[2, 3, 4], [[5, 6], 7, 8]]␤» 

(Any) method duckmap

Defined as:

method duckmap(&blockis rw is nodal

duckmap will apply &block on each element and return a new list with defined return values of the block. For undefined return values, duckmap will try to descend into the element if that element implements Iterable.

<a b c d e f g>.duckmap(-> $_ where <c d e>.any { .uc }).say;
# OUTPUT: «(a b C D E f g)␤» 
(('d''e'), 'f').duckmap(-> $_ where <e f>.any { .uc }).say;
# OUTPUT: «((d E) F)␤» 

(Any) method nodemap

Defined as:

method nodemap(&block --> Listis nodal

nodemap will apply &block to each element and return a new List with the return values of &block. In contrast to deepmap it will not descend recursively into sublists if it finds elements which does the Iterable role.

say [[1,2,3], [[4,5],6,7], 7].nodemap(*+1);
# OUTPUT: «(4, 4, 8)␤» 
 
say [[23], [4, [56]]]».nodemap(*+1)
# OUTPUT: «((3 4) (5 3))␤» 

The examples above would have produced the exact same results if we had used map instead of nodemap. The difference between the two lies in the fact that map flattens out slips while nodemap doesn't.

say [[2,3], [[4,5],6,7], 7].nodemap({.elems == 1 ?? $_ !! slip});
# OUTPUT: «(() () 7)␤» 
say [[2,3], [[4,5],6,7], 7].map({.elems == 1 ?? $_ !! slip});
# OUTPUT: «(7)␤» 

(Any) method flat

Defined as:

method flat(--> Seq:Dis nodal

Interprets the invocant as a list, flattens non-containerized Iterables into a flat list, and returns that list. Keep in mind Map and Hash types are Iterable and so will be flattened into lists of pairs.

say ((12), (3), %(:42a));      # OUTPUT: «((1 2) 3 {a => 42})␤» 
say ((12), (3), %(:42a)).flat# OUTPUT: «(1 2 3 a => 42)␤» 

Note that Arrays containerize their elements by default, and so flat will not flatten them. You can use hyper method call to call .List method on all the inner Iterables and so de-containerize them, so that flat can flatten them:

say [[123], [(45), 67]]      .flat# OUTPUT: «([1 2 3] [(4 5) 6 7])␤» 
say [[123], [(45), 67]]».List.flat# OUTPUT: «(1 2 3 4 5 6 7)␤» 

For more fine-tuned options, see deepmap, duckmap, and signature destructuring

(Any) method eager

Defined as:

method eager(--> Seq:Dis nodal

Interprets the invocant as a list, evaluates it eagerly, and returns that list.

say (1..10).eager;              # OUTPUT: «(1 2 3 4 5 6 7 8 9 10)␤» 

(Any) method elems

Defined as:

method elems(--> Int:Dis nodal

Interprets the invocant as a list, and returns the number of elements in the list.

say 42.elems;                   # OUTPUT: «1␤» 
say <a b c>.elems;              # OUTPUT: «3␤» 

(Any) method end

method end(--> Any:Dis nodal

Interprets the invocant as a list, and returns the last index of that list.

say 6.end;                      # OUTPUT: «0␤» 
say <a b c>.end;                # OUTPUT: «2␤» 

(Any) method pairup

Defined as:

method pairup(--> Seq:Dis nodal

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 (=> 1'b''c').pairup.perl;     # OUTPUT: «(:a(1), :b("c")).Seq␤» 

(Any) sub exit

Defined as:

sub exit(Int() $status = 0)

Exits the current process with return code $status.

(Any) sub item

Defined as:

proto sub item(|) is pure
multi sub item(\x)
multi sub item(|c)
multi sub item(Mu $a)

Forces given object to be evaluated in item context and returns the value of it.

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

You can also use $ as item contextualizer.

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

(Any) method Array

Defined as:

method Array(--> Array:Dis nodal

Coerce the invocant to Array.

(Any) method List

Defined as:

method List(--> List:Dis nodal

Coerce the invocant to List.

(Any) method Hash

Defined as:

method Hash(--> Hash:Dis nodal

Coerce the invocant to Hash.

(Any) method hash

Defined as:

method hash(--> Hash:Dis nodal

Coerce the invocant to Hash.

(Any) method Slip

Defined as:

method Slip(--> Slip:Dis nodal

Coerce the invocant to Slip.

(Any) method Map

Defined as:

method Map(--> Map:Dis nodal

Coerce the invocant to Map.

(Any) method Bag

Defined as:

method Bag(--> Bag:Dis nodal

Coerce the invocant to Bag, whereby Positionals are treated as lists of values.

(Any) method BagHash

Defined as:

method BagHash(--> BagHash:Dis nodal

Coerce the invocant to BagHash, whereby Positionals are treated as lists of values.

(Any) method Set

Defined as:

method Set(--> Set:Dis nodal

Coerce the invocant to Set, whereby Positionals are treated as lists of values.

(Any) method SetHash

Defined as:

method SetHash(--> SetHash:Dis nodal

Coerce the invocant to SetHash, whereby Positionals are treated as lists of values.

(Any) method Mix

Defined as:

method Mix(--> Mix:Dis nodal

Coerce the invocant to Mix, whereby Positionals are treated as lists of values.

(Any) method MixHash

Defined as:

method MixHash(--> MixHash:Dis nodal

Coerce the invocant to MixHash, whereby Positionals are treated as lists of values.

(Any) method Supply

Defined as:

method Supply(--> Supply:Dis nodal

Coerce the invocant first to a List and then to a Supply.

(Any) method min

Defined As:

multi method min(--> Any:D)
multi method min(&filter --> Any:D)

Coerces to Iterable and returns the numerically smallest element.

If a Callable positional argument is provided, each value is passed into the filter, and its return value is compared instead of the original value. The original value is still the one returned from min.

    say (1,7,3).min();       # OUTPUT:«1␤» 
    say (1,7,3).min({1/$_}); # OUTPUT:«7␤» 

(Any) method max

Defined As:

multi method max(--> Any:D)
multi method max(&filter --> Any:D)

Coerces to Iterable and returns the numerically largest element.

If a Callable positional argument is provided, each value is passed into the filter, and its return value is compared instead of the original value. The original value is still the one returned from max.

    say (1,7,3).max();       # OUTPUT:«7␤» 
    say (1,7,3).max({1/$_}); # OUTPUT:«1␤» 

(Any) method minmax

Defined As:

multi method minmax(--> Range:D)
multi method minmax(&filter --> Range:D)

Returns a Range from the smallest to the largest element.

If a Callable positional argument is provided, each value is passed into the filter, and its return value is compared instead of the original value. The original values are still used in the returned Range.

    say (1,7,3).minmax();      # OUTPUT:«1..7␤» 
    say (1,7,3).minmax({-$_}); # OUTPUT:«7..1␤» 

(Any) method minpairs

Defined As:

multi method minpairs(Any:D: --> Seq:D)

Calls .pairs and returns a Seq with all of the Pairs with minimum values, as judged by the cmp operator:

<a b c a b c>.minpairs.perl.put# OUTPUT: «(0 => "a", 3 => "a").Seq␤» 
%(:42a, :75b).minpairs.perl.put# OUTPUT: «(:a(42),).Seq␤» 

(Any) method maxpairs

Defined As:

multi method maxpairs(Any:D: --> Seq:D)

Calls .pairs and returns a Seq with all of the Pairs with maximum values, as judged by the cmp operator:

<a b c a b c>.maxpairs.perl.put# OUTPUT: «(2 => "c", 5 => "c").Seq␤» 
%(:42a, :75b).maxpairs.perl.put# OUTPUT: «(:b(75),).Seq␤» 

(Any) method sum

Defined As:

    method sum(--> TODO)

TODO

(Any) method keys

Defined As:

    method keys(--> TODO)

TODO

(Any) method flatmap

Defined As:

    method flatmap(--> TODO)

TODO

(Any) method roll

Defined As:

    method roll(--> TODO)

TODO

(Any) method pick

Defined As:

    method pick(--> TODO)

TODO

(Any) method head

Defined As:

    method head(--> TODO)

TODO

(Any) method tail

Defined As:

    method tail(--> TODO)

TODO

(Any) method skip

Defined As:

    method skip(--> TODO)

TODO

(Any) method prepend

Defined As:

    method prepend(--> TODO)

TODO

(Any) method unshift

Defined As:

    method unshift(--> TODO)

TODO

(Any) method first

Defined As:

    method first(--> TODO)

TODO

(Any) method unique

Defined As:

    method unique

Treats the Any as a 1-item list and uses List.unique on it.

(Any) method repeated

Defined As:

    method repeated(--> TODO)

TODO

(Any) method squish

Defined As:

    method squish(--> TODO)

TODO

(Any) method reduce

Defined As:

    method reduce(--> TODO)

TODO

(Any) method permutations

Defined As:

    method permutations(--> TODO)

TODO

(Any) method categorize

Defined As:

    method categorize(--> TODO)

TODO

(Any) method classify

Defined As:

    method classify(--> TODO)

TODO

(Any) method produce

Defined As:

    method produce(--> TODO)

TODO

(Any) method rotor

Defined As:

    method rotor(--> TODO)

TODO

(Any) method pairs

Defined As:

    method pairs(--> TODO)

TODO

(Any) method antipairs

Defined As:

    method antipairs(--> TODO)

TODO

(Any) method kv

Defined As:

    method kv(--> TODO)

TODO

(Any) method tree

Defined As:

    method tree(--> TODO)

TODO

(Any) method nl-out

Defined As:

    method nl-out(--> TODO)

TODO

(Any) method invert

Defined As:

    method invert(--> TODO)

TODO

(Any) method combinations

Defined As:

    method combinations(--> TODO)

TODO

(Any) method print-nl

Defined As:

    method print-nl(--> TODO)

TODO

(Any) method iterator

Defined As:

    method iterator(--> TODO)

TODO

(Any) method grep

Defined As:

    method grep(--> TODO)

TODO

(Any) method match

Defined As:

    method match(--> TODO)

TODO

(Any) method append

Defined As:

    method append(--> TODO)

TODO

(Any) method join

Defined As:

    method join(--> TODO)

TODO

(Any) method values

Defined As:

    method values(--> TODO)

TODO

(Any) method collate

Defined As:

    method collate(--> TODO)

TODO

(Any) method batch

Defined As:

    method batch(--> TODO)

TODO

(Any) method cache

Defined As:

    method cache(--> TODO)

TODO

Routines supplied by class Mu

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

(Mu) routine defined

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

Returns False on the type object, and True otherwise.

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

Very few types (like Failure) override defined to return False even for instances:

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

(Mu) routine isa

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

Returns True if the invocant is an instance of class $type, a subset type or a derived class (through inheritance) of $type.

my $i = 17;
say $i.isa("Int");   # OUTPUT: «True␤» 
say $i.isa(Any);     # OUTPUT: «True␤» 

A more idiomatic way to do this is to use the smartmatch operator ~~ instead.

my $s = "String";
say $s ~~ Str;       # OUTPUT: «True␤» 

(Mu) routine does

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

Returns True if and only if the invocant conforms to type $type.

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

Using the smart match operator ~~ is a more idiomatic alternative.

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

(Mu) routine Bool

multi sub    Bool(Mu --> Bool:D)
multi method Bool(   --> 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;                    # OUTPUT: «False␤» 
say Mu.new.Bool;                # OUTPUT: «True␤» 
say [123].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␤» 

(Mu) method Capture

Defined as:

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

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

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

(Mu) 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. 

(Mu) 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, for non-Str types, so say $something and say $something.gist generally produce the same output.

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

(Mu) routine perl

multi sub    perl(Mu --> Str)
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

(Mu) 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"␤» 

(Mu) method self

method self(--> Mu)

Returns the object it is called on.

(Mu) method clone

method clone(*%twiddles)

Creates a shallow clone of the invocant. Alternative values for public attributes can be provided via named arguments with names matching the attributes' names.

class Point2D {
    has ($.x$.y);
    multi method gist(Point2D:D:{
        "Point($.x$.y)";
    }
}
 
my $p = Point2D.new(x => 2=> 3);
 
say $p;                     # OUTPUT: «Point(2, 3)␤» 
say $p.clone(=> -5);      # OUTPUT: «Point(2, -5)␤» 

(Mu) 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.

(Mu) method bless

method bless(*%attrinit --> 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(-11);

(Though each time you write a custom constructor, remember that it makes subclassing harder).

(Mu) method CREATE

method CREATE(--> Mu:D)

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

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

(Mu) method print

multi method print(--> Bool:D)

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

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

(Mu) method put

multi method put(--> Bool:D)

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

"abc".put;              # RESULT: «abc␤» 

(Mu) method say

multi method say(--> Bool:D)

Prints value to $*OUT after stringification using .gist method with newline at end. To produce machine readable output use .put.

say 42;                 # OUTPUT: «42␤» 

(Mu) 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;           # 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.

(Mu) method WHICH

multi method WHICH(--> 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;       # OUTPUT: «True␤» 

(Mu) method WHERE

method WHERE(--> Int)

Returns an Int representing the memory address of the object.

(Mu) 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;
# OUTPUT: «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.

(Mu) 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.

See Exporting and Selective Importing Modules for more details.

(Mu) 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 { (1|2|3).return };
dd f(); # OUTPUT: «any(1, 2, 3)␤» 

(Mu) method return-rw

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

(Mu) method emit

method emit()

Emits the invocant into the enclosing supply or react block.

react { whenever supply { .emit for "foo"42.5 } {
    say "received {.^name} ($_)";
}}
 
# OUTPUT: 
# received Str (foo) 
# received Int (42) 
# received Rat (0.5) 

(Mu) method take

method take()

Returns the invocant in the enclosing gather block.

sub insert($sep+@list{
    gather for @list {
        FIRST .takenext;
        take slip $sep.item
    }
}
 
say insert ':', <a b c>;
# OUTPUT: «(a : b : c)␤» 

(Mu) routine take

sub take(\item)

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

(Mu) routine take-rw

sub take-rw(\item)

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

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

(Mu) 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(@argseq '-v' | '-V';
if $verbose-selected.so {
    say "Verbose option detected in arguments";
} # OUTPUT: «Verbose option detected in arguments␤» 

(Mu) 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(@argseq '-v' | '-V';
if $verbose-selected.not {
    say "Verbose option not present in arguments";
} # OUTPUT: «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(@argseq '-v' | '-V';
if not $verbose-selected {
    say "Verbose option not present in arguments";
} # OUTPUT: «Verbose option not present in arguments␤»