在Rossetta代码the Perl 6 code for Levenshtein distance上,子例程签名包含Str $t --> Int
。
-->
是操作员对$t
还是其他东西起作用?
例如,此代码要求返回值是整数:
sub add (Int $inputA, Int $inputB --> Int)
{
my $result = $inputA+$inputB;
say $result; # Oops, this is the last statement, so its return value is used for the subroutine
}
my $sum = add(5,6);
并且由于最后一条语句为say
函数,因此它隐式返回布尔值,因此会引发错误:
11
Type check failed for return value; expected 'Int' but got 'Bool'
in any return_error at src/vm/moar/Perl6/Ops.nqp:649
in sub add at test.p6:5
in block <unit> at test.p6:8
当您收到此错误时,您将查看代码并意识到应该包含一个显式的return语句,并且可能在子例程外部打印了结果:
sub add (Int $inputA, Int $inputB --> Int)
{
my $result = $inputA+$inputB;
return $result;
}
my $sum = add(5,6);
say $sum;
将打印出预期的答案,没有任何错误:
11
更清晰的定义返回类型的方法是使用returns
(谢谢Brad Gilbert):
sub add (Int $inputA, Int $inputB) returns Int
{
my $result = $inputA+$inputB;
return $result;
}
my $sum = add(5,6);
say $sum;