Parameter list pattern
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.
sub f()# ^^^^ Signature of sub fmy method x()# ^^ Signature of a methodmy = sub (*)# ^^^^^ Signature of an anonymous functionfor <a b c> -># ^^ Signature of a Blockmy (, ) = 5, (6, 7, 8);# ^^^^^^^^ Signature of a variable declaratormy = :(, );# ^^^^^^^^ Standalone Signature object
Signature literals can be used to define the signature of a callback or a closure.
sub f(:(Int))sub will-work(Int)sub won't-work(Str)f();f();CATCH ;# OUTPUT: «X::TypeCheck::Binding::Parameter: Constraint type check failed in binding to parameter '&c'␤»f(-> Int );
Smartmatching signatures against a List is supported.
my = :(Int , Str );say (10, 'answer') ~~ ;# OUTPUT: «True␤»my = sub ( Str , Int ) ;say .signature ~~ :( Str, Int );# OUTPUT: «True␤»given# OUTPUT: «match␤»
It matches the second
when clause since
:($, $) represents a
Signature with two scalar, anonymous, arguments, which is a more general version of
When smartmatching against a Hash, the signature is assumed to consist of the keys of the Hash.
my = left => 1, right => 2;say ~~ :(:, :);# OUTPUT: «True␤»
A signature consists of zero or more parameters, separated by commas.
my = :(, , );sub add(, ) ;
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 (: , ) ; # first argument is the invocantsay Foo.whoami; # OUTPUT: «Well I'm class Foo, of course!␤»
Parameters can optionally have a type constraint (the default is
Any). These can be used to restrict the allowed input to a function.
my = :(Int , Str );
Type constraints can have any compile-time defined value
of Int where * > 0;sub divisors(Positive-integer ) ;divisors 2.5;# ERROR «Type check failed in binding to parameter '$n'; expected Positive-integer but got Rat (2.5) $n)»divisors -3;# ERROR: «Constraint type check failed in binding to parameter '$n'; expected Positive-integer but got Int (-3)»
Please note that in the code above type constraints are enforced at two different levels: the first level checks if it belongs to the type in which the subset is based, in this case
Int. If it fails, a
Type check error is produced. Once that filter is cleared, the constraint that defined the subset is checked, producing a
I<Constraint> type check error if it fails.
Anonymous arguments are fine too, if you don't actually need to refer to a parameter by name, for instance to distinguish between different signatures in a multi or to check the signature of a Callable.
my = :($, @, ); # two anonymous and a "normal" parameter= :(Int, Positional); # just a type is also fine (two parameters)sub baz(Str)
Type constraints may also be type captures.
sub f(Real where , Real where )
The code in
where clauses has some limitations: anything that produces side-effects (e.g. printing output, pulling from an iterator, or increasing a state variable) is not supported and may produce surprising results if used. Also, the code of the
where clause may run more than once for a single typecheck in some implementations.
where clause doesn't need to be a code block, anything on the right of the
where-clause will be used to smartmatch the argument against it. So you can also write:
multi factorial(Int $ where 0)multi factorial(Int )
The first of those can be shortened to
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:
-> where .so && .name ( sub one ); # WRONG!!-> where ( sub two ); # OK!-> 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
.name; if that is also
True use its value for smartmatching…". It's the result of
(.so && .name) is will be smartmatched against, but we want to check that both
.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 foo(, where * == ** 2)foo 2, 4; # OUTPUT: «4 is a square of 2␤»»# foo 2, 3;# OUTPUT: «Constraint type check failed in binding to parameter '$b'…»
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
sub f(Int , UInt ? where )
sub f(* where ) ;f(42);f(<a>);CATCH# OUTPUT: «␤Constraint type check failed in binding to parameter '@a' ...»
sub f(Int :);f :i<forty-two>;CATCH# OUTPUT: «X::TypeCheck::Binding::Parameter ==> Type check failed in# binding to parameter '$i'; expected Int but got Str ("forty-two")␤»
Normally, a type constraint only checks whether the value of the parameter is of the correct type. Crucially, both object instances and type objects will satisfy such a constraint as illustrated below:
say 42.^name; # OUTPUT: «Int␤»say 42 ~~ Int; # OUTPUT: «True␤»say Int ~~ Int; # OUTPUT: «True␤»
Note how both
Int satisfy the match.
Sometimes we need to distinguish between these object instances (
42) and type objects (
Int). Consider the following code:
sub limit-lines(Str , Int )say (limit-lines "a \n b \n c \n d \n", 3).perl; # "a \n b \n c \n d "say limit-lines Str, 3;CATCH ;# 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 "a \n b", Int # Always returns the max number of lines
Here we really only want to deal with string instances, not type objects. To do this, we can use the
:D type constraint. This constraint checks that the value passed is an object instance, in a similar fashion to calling its DEFINITE method.
To warm up, let's apply
:D to the right-hand side of our humble
say 42 ~~ Int; # OUTPUT: «True␤»say Int ~~ Int; # OUTPUT: «False␤»
Note how only
Int:D in the above.
limit-lines, we can now amend its signature to catch the error early:
sub limit-lines(Str , Int ) ;say limit-lines Str, 3;CATCH ;# 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 that type objects are the only ones that make sense for a routine to accept. This can be done with the
:U type constraint, which checks whether the value passed is a type object rather than an object instance. Here's our
Int example again, this time with
say 42 ~~ Int; # OUTPUT: «False␤»say Int ~~ Int; # OUTPUT: «True␤»
42 fails to match
Here's a more practical example:
sub can-turn-into(Str , Any )say can-turn-into("3", Int);say can-turn-into("6.5", Int);say can-turn-into("6.5", Num);say can-turn-into("a string", Num);# OUTPUT: True True True False
can-turn-into with an object instance as its second parameter will yield a constraint violation as intended:
say can-turn-into("a string", 123);# OUTPUT: «Parameter '$type' of routine 'can-turn-into' must be a type object of type 'Any', not an object instance of type 'Int'...»
For explicitly indicating the normal behaviour,
:_ can be used, but this is unnecessary.
:(Num:_ $) is the same as
To recap, here is a quick illustration of these type constraints, also known collectively as type smileys:
# Checking a type objectsay Int ~~ Any; # OUTPUT: «False␤»say Int ~~ Any; # OUTPUT: «True␤»say Int ~~ Any; # OUTPUT: «True␤»# Checking an object instancesay 42 ~~ Any; # OUTPUT: «True␤»say 42 ~~ Any; # OUTPUT: «False␤»say 42 ~~ Any; # OUTPUT: «True␤»# Checking a user-supplied class;say Foo ~~ Any; # OUTPUT: «False␤»say Foo ~~ Any; # OUTPUT: «True␤»say Foo ~~ Any; # OUTPUT: «True␤»my = Foo.new;say ~~ Any; # OUTPUT: «True␤»say ~~ Any; # OUTPUT: «False␤»say ~~ Any; # OUTPUT: «True␤»
The Classes and Objects document further elaborates on the concepts of instances and type objects and discovering them with the
Keep in mind all parameters have values; even optional ones have default defaults that are the type object of the constrained type for explicit type constraints. If no explicit type constraint exists, the default default is an Any type object for methods, submethods, and subroutines, and a Mu type object for blocks. This means that if you use the
:D type smiley, you'd need to provide a default value or make the parameter required. Otherwise, the default default would be a type object, which would fail the definiteness constraint.
sub divide (Int : = 2, Int :!)divide :1a, :2b; # OUTPUT: «0.5␤»
sub f(:(Int, Str)) ;sub g(Int , Str ) ;f();# OUTPUT: «ten10␤»
This shorthand syntax is available only for parameters with the
& sigil. For others, you need to use the long version:
sub f( where .signature ~~ :(Int, Str))sub g(Num , Str )sub h(Int , Str )# f(&g); # Constraint type check failedf(); # OUTPUT: «ten10␤»
There are multiple ways to constrain return types on a Routine. All versions below are currently valid and will force a type check on successful execution of a routine.
sub foo(--> Int) ;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 --> Str) # Validsub greeting2(Str , --> Str) # Validsub favorite-number1(--> 42) # OUTPUT: 42sub favorite-number2(--> 42) # 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 --> 123)my = foo("hello"); # OUTPUT: hellosay ; # OUTPUT: 123
# The code below will not compilesub foo(Str --> 123)my = foo("hello");say ;
returns following a signature declaration has the same function as
--> with two caveats.
(1) This form is proposed for future removal. (2) This form does not work with constant values
sub greeting(Str ) returns Str # Valid
sub favorite-number returns 42 # This will fail.
of is just the real name of the
sub foo() of Int ; # 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 ; # Valid
my 42 sub bad-answer ; # This will fail.
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) , Str() )f '10', 10;# OUTPUT: «Int Str␤»use MONKEY;augment ;sub foo(Date(Str) ) ;foo "2016-12-01";# OUTPUT: «Date␤2016-12-01␤»
The coercion is performed by calling the method with the name of the type to coerce to, if it exists (e.g.
Foo(Bar) coercer, would call method
Foo). The method is assumed to return the correct type—no additional checks on the result are currently performed.
Coercion can also be performed on return types:
sub square-str (Int --> Str(Int))for 2,4, *² … 256 -># OUTPUT: «2² is 1 figures long␤# 4² is 2 figures long␤# 16² is 3 figures long␤# 256² is 5 figures long␤»
In this example, coercing the return type to
String allows us to directly apply string methods, such as the number of characters.
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.
$ = :(, ); # exactly two arguments, where the second one must be Positional$ = :(, *); # at least one argument, @b slurps up any beyond that$ = :(*); # no positional arguments, but any number of named argumentssub one-arg (@)sub slurpy (*@)one-arg (5, 6, 7); # ok, same as one-arg((5, 6, 7))slurpy (5, 6, 7); # okslurpy 5, 6, 7 ; # ok# one-arg(5, 6, 7) ; # X::TypeCheck::Argument# one-arg 5, 6, 7 ; # X::TypeCheck::Argumentsub named-names (*) ;say named-names :foo(42) :bar<baz>; # OUTPUT: «foo bar␤»
Note that positional parameters aren't allowed after slurpy parameters.
:(*, );# ===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.
There are three variations to slurpy array parameters.
The single asterisk form flattens passed arguments.
The double asterisk form does not flatten arguments.
The plus form flattens according to the single argument rule.
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.
Slurpy parameters declared with one asterisk will flatten arguments by dissolving one or more layers of bare Iterables.
my = <a b c>;my := <d e f>;sub a(*) ;a(); # OUTPUT: «["a", "b", "c"]»a(1, , [2, 3]); # OUTPUT: «[1, "d", "e", "f", 2, 3]»a([1, 2]); # OUTPUT: «[1, 2]»a(1, [1, 2], ([3, 4], 5)); # OUTPUT: «[1, 1, 2, 3, 4 5]»a(( for 1, 2, 3)); # OUTPUT: «[1, 2, 3]»
A single asterisk slurpy flattens all given iterables, effectively hoisting any object created with commas up to the top level.
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 = <a b c>;my := <d e f>;sub b(**) ;b(); # OUTPUT: «[["a", "b", "c"],]␤»b(1, , [2, 3]); # OUTPUT: «[1, ("d", "e", "f"), [2, 3]]␤»b([1, 2]); # OUTPUT: «[[1, 2],]␤»b(1, [1, 2], ([3, 4], 5)); # OUTPUT: «[1, [1, 2], ([3, 4], 5)]␤»b(( for 1, 2, 3)); # OUTPUT: «[(1, 2, 3),]␤»
The double asterisk slurpy hides the nested comma objects and leaves them as-is in the slurpy array.
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 = <a b c>;my := <d e f>;sub c(+) ;c(); # OUTPUT: «["a", "b", "c"]␤»c(1, , [2, 3]); # OUTPUT: «[1, ("d", "e", "f"), [2, 3]]␤»c([1, 2]); # OUTPUT: «[1, 2]␤»c(1, [1, 2], ([3, 4], 5)); # OUTPUT: «[1, [1, 2], ([3, 4], 5)]␤»c(( for 1, 2, 3)); # OUTPUT: «[1, 2, 3]␤»
For additional discussion and examples, see Slurpy Conventions for Functions.
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 , T , ::C)# 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 = f(10, 2, Int.new / Int.new);say s(2); # 10 / 2 * 2 == 10
An argument can be positional or named. By default, arguments are positional, except slurpy hash and arguments marked with a leading colon
:. The latter is called a colon-pair. Check the following signatures and what they denote:
$ = :(); # a positional argument$ = :(:); # a named argument of name 'a'$ = :(*); # a slurpy positional argument$ = :(*); # a slurpy named argument
On the caller side, positional arguments are passed in the same order as the arguments are declared.
sub pos(, )pos(4, 5); # OUTPUT: «x=4 y=5»
In the case of named arguments and parameters, only the name is used for mapping arguments to parameters. If a fat arrow is used to construct a Pair only those with valid identifiers as keys are recognized as named arguments.
sub named(:, :)named( y => 5, x => 4); # OUTPUT: «x=4 y=5»
You can invoke the routine using a variable with the same name as the named argument; in that case
: will be used for the invocation so that the name of the variable is understood as the key of the argument.
sub named-shortcut( : )named-shortcut( shortcut => "to here"); # OUTPUT: «Looks like to here␤»my = "Þor is mighty";named-shortcut( : ); # OUTPUT: «Looks like Þor is mighty␤»
It is possible to have a different name for a named argument than the variable name:
sub named(:official())named :official;
The colon-pair syntax can be used to provide aliases for arguments:
sub alias-named(:color(:), :type(:class()))alias-named(color => "red", type => "A"); # both names can be usedalias-named(colour => "green", type => "B"); # more than two names are okalias-named(color => "white", class => "C"); # every alias is independent
The presence of the colon
: will decide whether we are creating a new named argument or not.
:$colour will not only be the name of the aliased variable, but also a new named argument (used in the second invocation). However,
$kind will just be the name of the aliased variable, that does not create a new named argument. More uses of aliases can be found in sub MAIN
A function with named arguments can be called dynamically, dereferencing a Pair with
| to turn it into a named argument.
multi f(:) ;multi f(:) ;for 'named', 'also-named' ->my = :named(1);f |; # OUTPUT: «(:$named)␤»
The same can be used to convert a
Hash into named arguments.
sub f(:) ;my = also-named => 4;f |; # OUTPUT: «(:$also-named)␤»
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.
;my = <x y z> Z=> (5, 20, [1,2]);say C.new(|.Map);# OUTPUT: «C.new(x => 5, y => 20, z => [1, 2])␤»
Positional parameters are mandatory by default, and can be made optional with a default value or a trailing question mark:
$ = :(Str ); # required parameter$ = :( = 10); # optional parameter, default value 10$ = :(Int ?); # optional parameter, default is the Int type object
$ = :(:); # optional parameter$ = :(: = False); # optional parameter, defaults to False$ = :(:!); # mandatory 'name' named parameter
Default values can depend on previous parameters, and are (at least notionally) computed anew for each call
$ = :(, = / 100);$ = :(: = ['.', '..']); # a new Array for every call
Dynamic variables are allowed in signatures although they don't provide special behaviour because argument binding does connect two scopes anyway.
Parameters can be followed by a sub-signature in parentheses, which will destructure the argument given. The destructuring of a list is just its elements:
sub first( (, *))
sub first([, *@])
While the destructuring of a hash is its pairs:
sub all-dimensions(% (:length(:), :width(:), :depth(:)))
Pointy loops can also destructure hashes, allowing assignment to variables:
my = (:40life, :41universe, :42everything);for -> (:, :)# OUTPUT: «universe → 41␤life → 40␤everything → 42␤»
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(), :value())
However, this unpacking of objects as their attributes is only the default behavior. To make an object get destructured differently, change its
To match against a compound parameter use a sub-signature following the argument name in parentheses.
sub foo(|c(Int, Str));foo(42, "answer");# OUTPUT: «called with \(42, "answer")␤»
To exclude certain parameters from being considered in multiple dispatch, separate them with a double semicolon.
multi sub f(Int , Str ;; :) ;f(10, 'answer');# OUTPUT: «10, answer, Any␤»
Prefixing a parameter with a vertical bar
| makes the parameter a
Capture, using up all the remaining positional and named arguments.
If bound to a variable arguments can be forwarded as a whole using the slip operator
sub a(Int , Str )sub b(|c)b(42, "answer");# OUTPUT: «Capture␤Int Str␤»
By default, parameters are bound to their argument and marked as read-only. One can change that with traits on the parameter.
sub count-up( is copy)
sub swap( is rw, is rw)
On slurpy parameters,
is rw is reserved for future use by language designers.
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( is copy where m:i/^**3..39$/)
method params(Signature: --> Positional)
Returns the list of
Parameter objects that make up the signature.
method arity(Signature: --> Int)
Returns the minimal number of positional arguments required to satisfy the signature.
method count(Signature: --> Real)
Returns the maximal number of positional arguments which can be bound to the signature. Returns
Inf if there is a slurpy positional parameter.
Whatever the Signature's return constraint is:
:(, --> Int).returns # OUTPUT: «(Int)»
multi method ACCEPTS(Signature: Signature )multi method ACCEPTS(Signature: Capture )multi method ACCEPTS(Signature: Mu \topic)
$topic is a Signature returns
True if anything accepted by
$topic would also be accepted by the invocant, otherwise returns
:(, ) ~~ :(, , ?); # OUTPUT: «True»:(Int ) ~~ :(Str); # OUTPUT: «False»
$topic is a Capture, returns
True if it can be bound to the invocant, i.e., if a function with invocant's
Signature would be able to be called with the
\(1, 2, :foo) ~~ :(, , :foo()); # OUTPUT: «True»\(1, :bar) ~~ :(); # OUTPUT: «False»
<a b c d> ~~ :(Int ); # OUTPUT: «False»42 ~~ :(Int); # OUTPUT: «False» (Int.Capture throws)set(<a b>) ~~ :(:, :); # OUTPUT: «True»
where clauses are not introspectable, the method cannot determine whether two signatures ACCEPTS the same sort of
where-constrained parameters. Such comparisons will return
False. This includes signatures with literals, which are just sugar for the
say :(42) ~~ :($ where 42) # OUTPUT: «False␤»