This comes from this
perl6/doc
issue which also refers to these questions in the IRC channel
The documentation specifies how to constrain the arguments of a callable using a Signature literal:
sub f(&c:(Int, Str)) { say c(10, 'ten') };
(this would restrict the function argument to only those that take an Integer and a String as an argument).
However, in some other situations, where
constraining can be used, for instance if you need to restrict the arity or the return values. However, is there any simpler way or syntax of doing this?
To enforce an arity of, for example, 2, then a signature literal can also be used:
sub foo(&x:($,$)) {
x(1,2)
}
Then this works:
foo -> $a, $b { say $a + $b }
While this dies:
foo -> $a { say $a }
This signature literal just means "any two arguments". The return type can also be constrained by similar means:
sub foo(&x:(--> Int)) {
say x()
}
Meaning this works:
foo sub (--> Int) { 42 }
But this dies:
foo sub () { "oops" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With