Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we specify the attributes of a Callable argument in a subroutine

Tags:

signature

raku

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?

like image 649
jjmerelo Avatar asked Dec 09 '18 09:12

jjmerelo


1 Answers

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" }
like image 146
Jonathan Worthington Avatar answered Nov 15 '22 09:11

Jonathan Worthington