-在Perl 6中是什么意思?

问题描述 投票:1回答:1

在Rossetta代码the Perl 6 code for Levenshtein distance上,子例程签名包含Str $t --> Int

-->是操作员对$t还是其他东西起作用?

syntax perl6 raku
1个回答
3
投票

它指定return constraint

例如,此代码要求返回值是整数:

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;
© www.soinside.com 2019 - 2024. All rights reserved.