我们如何在子例程中指定 Callable 参数的属性
How can we specify the attributes of a Callable argument in a subroutine
This comes from this perl6/doc
issue which also refers to these questions in the IRC channel
documentation specifies how to constrain the arguments of a callable using a Signature literal:
sub f(&c:(Int, Str)) { say c(10, 'ten') };
(这会将函数参数限制为仅接受整数和字符串作为参数的参数)。
然而,在其他一些情况下,可以使用 where
约束,例如,如果您需要限制元数或 return 值。但是,有没有更简单的方法或语法来做到这一点?
要强制执行元数,例如 2,那么也可以使用签名文字:
sub foo(&x:($,$)) {
x(1,2)
}
然后这个有效:
foo -> $a, $b { say $a + $b }
虽然它死了:
foo -> $a { say $a }
这个签名字面意思就是"any two arguments"。 return 类型也可以通过类似的方式进行约束:
sub foo(&x:(--> Int)) {
say x()
}
意思是这个有效:
foo sub (--> Int) { 42 }
但是这个死了:
foo sub () { "oops" }
This comes from this
perl6/doc
issue which also refers to these questions in the IRC channel
documentation specifies how to constrain the arguments of a callable using a Signature literal:
sub f(&c:(Int, Str)) { say c(10, 'ten') };
(这会将函数参数限制为仅接受整数和字符串作为参数的参数)。
然而,在其他一些情况下,可以使用 where
约束,例如,如果您需要限制元数或 return 值。但是,有没有更简单的方法或语法来做到这一点?
要强制执行元数,例如 2,那么也可以使用签名文字:
sub foo(&x:($,$)) {
x(1,2)
}
然后这个有效:
foo -> $a, $b { say $a + $b }
虽然它死了:
foo -> $a { say $a }
这个签名字面意思就是"any two arguments"。 return 类型也可以通过类似的方式进行约束:
sub foo(&x:(--> Int)) {
say x()
}
意思是这个有效:
foo sub (--> Int) { 42 }
但是这个死了:
foo sub () { "oops" }