在罗塞塔代码(Levenshtein distance 的 Perl 6 代码)上,子例程签名包含Str $t --> Int
.
操作员是在-->
起作用$t
还是完全在其他方面?
在罗塞塔代码(Levenshtein distance 的 Perl 6 代码)上,子例程签名包含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;