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() # ^^^^ Signature of sub f my method x() # ^^ Signature of a method my = sub (*) # ^^^^^ Signature of an anonymous function for <a b c> -> # ^^ Signature of a Block my (, ) = 5, (6, 7, 8);# ^^^^^^^^ Signature of a variable declarator my = :(, );# ^^^^^^^^ 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 );
You can use any kind of literal, including numeric ones, as part of a signature; this is generally used in conjunction with multis
proto sub stuff(|) multi sub stuff(33) multi sub stuff(⅓) multi sub stuff(Int) multi sub stuff(Complex) say stuff() for (33, ⅓, i, 48); # OUTPUT: «5843663»
However, you can't use True
or False
as literals in signatures since they will always succeed (or fail). A warning will be issued if you do so:
sub foo(True) {}; my $sig = :( True );
They will both warn "Literal values in signatures are smartmatched against and smartmatch with True
will always succeed. Use the where
clause instead.". Use of False
will produce a similar warning.
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 $sig
.
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»
Signature
literals can contain string/numeric literals
my = :('Þor', Str, Int);say <Þor Hammer 1> ~~ ; # OUTPUT: «True»
And they can also contain the invocant marker
;say Foo.^methods.first(*.name eq 'bar').signature ~~ :($: *%) ;# OUTPUT: «True»
Parameter separators §
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. This is done in order to distinguish it from what would then be a regular positional parameter. 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 invocant 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 = :(Int , Str );
Type constraints can have any compile-time defined value
of Int where * > 0;sub divisors(Positive-integer ) ;CATCH ; divisors 2.5;# OUTPUT: «X::TypeCheck::Binding::Parameter: Type check failed in binding to parameter '$n'; expected Positive-integer but got Rat (2.5)» divisors -3;# OUTPUT: «X::TypeCheck::Binding::Parameter: 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 Constraint type check
error if it fails.
Type constraints can define multiple allowable types
sub abbrev( where Str|List|Hash) # throws if $arg is not one of those types
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.
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 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.
The 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
multi factorial(0)
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 a 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)
it will be smartmatched 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 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'…»
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 , UInt ? where )
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(* where ) ;f(42);f(<a>);CATCH # 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 :);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")»
Constraining argument definiteness §
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 42
and 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).raku; # "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 (meta)method.
To warm up, let's apply :D
to the right-hand side of our humble Int
example:
say 42 ~~ Int; # OUTPUT: «True» say Int ~~ Int; # OUTPUT: «False»
Note how only 42
matches Int:D
in the above.
Returning to 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 :U
applied:
say 42 ~~ Int; # OUTPUT: «False» say Int ~~ Int; # OUTPUT: «True»
Now 42
fails to match Int:U
while Int
succeeds.
Here's a more practical example:
sub can-turn-into(Str , Any ) say can-turn-into("3", Int); # OUTPUT: «True» say can-turn-into("6.5", Int); # OUTPUT: «True» say can-turn-into("6.5", Num); # OUTPUT: «True» say can-turn-into("a string", Num); # OUTPUT: «False»
Calling 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 behavior, that is, not constraining whether the argument will be an instance or a type object, :_
can be used but this is unnecessary since this is the default constraint (of this kind) on arguments. Thus, :(Num:_ $)
is the same as :(Num $)
.
To recap, here is a quick illustration of these type constraints, also known collectively as type smileys:
# Checking a type object say Int ~~ Any; # OUTPUT: «False» say Int ~~ Any; # OUTPUT: «True» say Int ~~ Any; # OUTPUT: «True» # Checking a subset of Int where * // 2;say 3 ~~ Even; # OUTPUT: «True» say 3 ~~ Even; # OUTPUT: «False» say Int ~~ Even; # OUTPUT: «True» # Checking an object instance say 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» # Checking an instance of a class 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 .DEFINITE
method.
Keep in mind all parameters have values; even optional ones have default values that are the type object of the constrained type for explicit type constraints. If no explicit type constraint exists, the default value 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 value would be a type object, which would fail the definiteness constraint.
sub divide (Int : = 2, Int :!) divide :1a, :2b; # OUTPUT: «0.5»
The default value will kick in when that particular parameter, either positional or named, gets no value at all.
sub f( = 42);f; # OUTPUT: «4242» f Nil; # OUTPUT: «Nilanswer»
$a
has 42 as its default value. With no value, $a
will be assigned the default value declared in the Signature
. However, in the second case, it does receive a value, which happens to be Nil
. Assigning Nil
to any variable resets it to its default value, which has been declared as 'answer'
by use of the default trait. That explains what happens the second time we call f
. Routine parameters and variables deal differently with default value, which is in part clarified by the different way default values are declared in each case (using =
for parameters, using the default
trait for variables).
Note: in 6.c language, the default value of :U
/:D
constrained variables was a type object with such a constraint, which is not initializable, thus you cannot use the .=
operator, for example.
use v6.c;my Int .= new: 42;# OUTPUT: You cannot create an instance of this type (Int:D) # in block <unit> at -e line 1
In the 6.d language, the default default is the type object without the smiley constraint:
use v6.d;my Int .= new: 42; # OUTPUT: «42»
A closing remark on terminology: this section is about the use of the type smileys :D
and :U
to constrain the definiteness of arguments. Occasionally definedness is used as a synonym for definiteness; this may be confusing, since the terms have subtly different meanings.
As explained above, definiteness is concerned with the distinction between type objects and object instances. A type object is always indefinite, while an object instance is always definite. Whether an object is a type object/indefinite or an object instance/definite can be verified using the DEFINITE (meta)method.
Definiteness should be distinguished from definedness, which is concerned with the difference between defined and undefined objects. Whether an object is defined or undefined can be verified using the defined
-method, which is implemented in class Mu. By default a type object is considered undefined, while an object instance is considered defined; that is: .defined
returns False
on a type object, and True
otherwise. But this default behavior may be overridden by subclasses. An example of a subclass that overrides the default .defined
behavior is Failure, so that even an instantiated Failure
acts as an undefined value:
my = Failure; # Initialize with type object my = Failure.new("foo"); # Initialize with object instance say .DEFINITE; # Output: «False» : indefinite type object say .DEFINITE; # Output: «True» : definite object instance say .defined; # Output: «False» : default response say .defined; # Output: «False» : .defined override
Constraining signatures of Callable
s
§
The signature of a Callable parameter can be constrained by specifying a Signature literal right after the parameter (no whitespace allowed):
sub apply(:(Int --> Int), Int \n) sub identity(Int \i --> Int) sub double(Int \x --> Int) say apply , 10; # OUTPUT: «10» say apply , 10; # OUTPUT: «20»
Typed lambdas also work with constrained callable parameters.
say apply -> Int \x --> Int , 3; # OUTPUT: «6» say apply -> Int \x --> Int , 3; # OUTPUT: «27»
Note that this shorthand syntax is available only for parameters with the &
sigil. For others, you need to use the long version:
sub play-with-tens( where .signature ~~ :(Int, Str)) sub by-joining-them(Int , Str ) play-with-tens ; # OUTPUT: «ten10» play-with-tens -> Int \i, Str \s ; # OUTPUT: «tenten» sub g(Num , Str ) # play-with-tens(&g); # Constraint type check failed
Constraining return types §
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.
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) ;say foo.raku; # OUTPUT: «Nil»
Type captures are not supported.
Return type arrow: --
>
§
This form of indicating return types (or constants) in the signature is preferred, since it can handle constant values while the others can't. 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) # Valid sub greeting2(Str , --> Str) # Valid sub favorite-number1(--> 42) # OUTPUT: 42 sub 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: hello say ; # OUTPUT: 123
# The code below will not compile sub foo(Str $word --> 123) { say $word; return $word; } my $value = foo("hello"); say $value;
returns
§
The keyword returns
following a signature declaration has the same function as -->
with the caveat that this form does not work with constant values. You cannot use it in a block either. That is why the pointy arrow form is always preferred.
sub greeting(Str ) returns Str # Valid
sub favorite-number returns 42 { } # This will fail.
of
§
of
is just the real name of the returns
keyword.
sub foo() of Int ; # Valid
sub foo() of 42 { }; # This will fail.
prefix(C-like) form §
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.
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) , Str() ) f '10', 10;# OUTPUT: «Int Str» sub foo(Date(Str) ) ;foo "2016-12-01";# OUTPUT: «Date2016-12-01»
The coercion is performed by calling the method with the name of the type to coerce to, if it exists. In this example, we're calling the builtin method Date
on the Str
class. 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 Str
allows us to directly apply string methods, such as the number of characters.
Slurpy 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 make routines that use them variadic, and by extension are called variadic arguments. Here we will focus on slurpy parameters, or simply slurpies.
An array or hash parameter can be marked as slurpy by leading single (*) or double asterisk (**) or a leading plus (+). A slurpy parameter can bind to an arbitrary number of arguments (zero or more), and it will result in a type that is compatible with the sigil.
These are called "slurpy" because they slurp up any remaining arguments to a function, like someone slurping up noodles.
my = :(, ); # exactly two arguments, second must be Positional my = :(, *); # at least one argument, @b slurps up any beyond that my = :(*); # no positional arguments, but any number # of named arguments sub one-arg (@) sub slurpy (*@) one-arg (5, 6, 7); # ok, same as one-arg((5, 6, 7)) slurpy (5, 6, 7); # ok slurpy 5, 6, 7 ; # ok # one-arg(5, 6, 7) ; # X::TypeCheck::Argument # one-arg 5, 6, 7 ; # X::TypeCheck::Argument sub named-names (*) ;say named-names :foo(42) :bar<baz>; # OUTPUT: «foo bar»
Positional and named slurpies can be combined; named arguments (i.e., Pair
s) are collected in the specified hash, positional arguments in the array:
sub combined-slurpy (*, *) # or: sub combined-slurpy (*%h, *@a) { ... } say combined-slurpy(one => 1, two => 2);# OUTPUT: «{array => [], hash => {one => 1, two => 2}}» say combined-slurpy(one => 1, two => 2, 3, 4);# OUTPUT: «{array => [3 4], hash => {one => 1, two => 2}}» say combined-slurpy(one => 1, two => 2, 3, 4, five => 5);# OUTPUT: «{array => [3 4], hash => {five => 5, one => 1, two => 2}}» say combined-slurpy(one => 1, two => 2, 3, 4, five => 5, 6);# OUTPUT: «{array => [3 4 6], hash => {five => 5, one => 1, two => 2}}»
Note that positional parameters aren't allowed after slurpy (or, in fact, after any type of variadic) parameters:
:(*@args, $last); # ===SORRY!=== Error while compiling: # Cannot put required parameter $last after variadic parameters
Normally a slurpy parameter will create an Array (or compatible type), create a new Scalar container for each argument, and assign the value from each argument to those Scalar
s. If the original argument also had an intermediary Scalar
it is bypassed during this process, and is not available inside the called function.
Sigiled parameters will always impose a context on the collected arguments. Sigilless parameters can also be used slurpily, preceded by a + sign, to work with whatever initial type they started with:
sub zipi( +zape ) ;say zipi( "Hey "); # OUTPUT: «List => (Hey )» say zipi( 1...* ); # OUTPUT: «Seq => (...)»
Slurpy parameters have special behaviors when combined with some traits and modifiers, as described in the section on slurpy array parameters.
Methods automatically get a *%_
slurpy named parameter added if they don't have another slurpy named parameter declared.
Types of slurpy array parameters §
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.
Flattened slurpy §
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.
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 = <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.
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 = <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 §
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
Positional vs. named arguments §
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;
Argument aliases §
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 used alias-named(colour => "green", type => "B"); # more than two names are ok alias-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)»
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.
;my = <x y z> Z=> (5, 20, [1,2]);say C.new(|.Map);# OUTPUT: «C.new(x => 5, y => 20, z => [1, 2])»
You can create as many aliases to a named argument as you want:
sub alias-named(:color(:), :variety(:style(:sort(:type(:class()))))) say alias-named(color => "red", style => "A");say alias-named(colour => "green", variety => "B");say alias-named(color => "white", class => "C");
You can create named arguments that do not create any variables by making the argument an alias for an anonymous argument. This can be useful when using named arguments solely as a means of selecting a multi
candidate, which is often the case with traits, for instance:
# Timestamps calls to a routine. multi sub trait_mod:<is>(Routine is raw, :timestamped($)!) sub foo is timestamped foo;say +&foo.?timestamps; # OUTPUT: «1»
Optional and mandatory arguments §
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
Named parameters are optional by default, and can be made mandatory with a trailing exclamation mark:
= :(:); # 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 §
Dynamic variables are allowed in signatures although they don't provide special behavior because argument binding does connect two scopes anyway.
Destructuring arguments §
Non-scalar parameters can be followed or substituted by a sub-signature in parentheses, which will destructure the argument given. The destructuring of a list is just its elements:
sub first( (, *))
or
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 → 41life → 40everything → 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 Capture
method.
Sub-signatures §
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")»
Long names §
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»
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 , Str ) sub b(|c) b(42, "answer");# OUTPUT: «CaptureInt 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( is copy)
The is rw
trait, which stands for is read-write, 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( is rw, is rw)
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 or a plus sign 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 Scalar
s 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 Raku 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$/)
Methods §
method params §
method params(Signature: --> Positional)
Returns the list of Parameter
objects that make up the signature.
method arity §
method arity(Signature: --> Int)
Returns the minimal number of positional arguments required to satisfy the signature.
method count §
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.
method returns §
Whatever the Signature's return constraint is:
:(, --> Int).returns # OUTPUT: «(Int)»
method ACCEPTS §
multi method ACCEPTS(Signature: Signature )multi method ACCEPTS(Signature: Capture )multi method ACCEPTS(Signature: Mu \topic)
If $topic
is a Signature returns True
if anything accepted by $topic
would also be accepted by the invocant, otherwise returns False
:
:(, ) ~~ :(, , ?); # OUTPUT: «True» :(Int ) ~~ :(Str); # OUTPUT: «False»
The $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 $topic
:
\(1, 2, :foo) ~~ :(, , :foo()); # OUTPUT: «True» \(1, :bar) ~~ :(); # OUTPUT: «False»
Lastly, the candidate with Mu \topic
converts topic
to Capture and follows the same semantics as Capture $topic
:
<a b c d> ~~ :(Int ); # OUTPUT: «False» 42 ~~ :(Int); # OUTPUT: «False» (Int.Capture throws) set(<a b>) ~~ :(:, :); # OUTPUT: «True»
Since 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 where
-constraints:
say :(42) ~~ :($ where 42) # OUTPUT: «False»
method Capture §
Defined as:
method Capture()
Throws X::Cannot::Capture
.
Runtime creation of Signature objects (6.d, 2019.03 and later) §
Signature.new(params => (...), returns => Type, arity => 1, count => 1.Num)
In some situations, specifically when working with the MetaObject Protocol, it makes sense to create Signature
objects programmatically. For this purpose, you can call the new
method with the following named parameters:
params
A list of Parameter objects for this signature.
returns
Any constraint the return value should match. Defaults to Mu
, which effectively implies no return value constraint check.
arity
The minimal number of positional arguments required to satisfy the signature. Defaults to the number of Parameter
objects given with the params
parameter.
count
The maximal number of positional arguments which can be bound to the signature. Defaults to the arity
if not specified. Specify Inf
if there is a slurpy positional parameter.
Warning: although the logical type of the count
parameter is integer, the value assigned to it must explicitly be of type Num
. If any other type is used, the new
method silently fails and returns an empty signature. The same trouble occurs when the value assigned to the arity
parameter is not of type Int
.