You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

index()函数第三个参数的错误提示是否存在错误?

Is the error message for Raku's index() function incorrect?

Let's break this down clearly:

First, let's nail down why your code is throwing an error in the first place:

  • You declared my $foo; without assigning an initial value, so it starts as an undefined Any type (not the 0 you expected).
  • When you first call index $word, "a", $foo, you're passing an undefined value as the third $pos argument. Raku's index function requires this position argument to be a defined Cool type (marked as Cool:D in the signature), which your uninitialized $foo isn't.

Now, about the error message itself:
The core of the error message is accurate—it correctly flags that your call index(Str: Str, Any) doesn't match any valid signature for the function. The first three listed signatures are complete and correct:

  • (Str:D $: Cool:D $needle, *%_): Call with just a search needle (no starting position)
  • (Str:D $: Str:D $needle, *%_): Same as above, but explicitly for string needles
  • (Str:D $: Cool:D $needle, Cool:D $pos, *%_): Call with a needle plus a defined starting position

The only issue is the fourth signature in the list: (Str:D $: Str:D $needle, ... — this is truncated. It should fully display the signature for a string needle plus a defined position, like (Str:D $: Str:D $needle, Cool:D $pos, *%_). That truncation is a minor formatting flaw in the error message, but it doesn't undermine the correct core diagnosis: your uninitialized variable doesn't meet the type requirements for index's third argument.

To fix your code, just initialize $foo to 0 instead of leaving it undefined:

sub count-a {
    my $word = "banana";
    my $count = 0;
    my $foo = 0; # Initialize to the starting position you intended
    while True {
        $foo = index $word, "a", $foo;
        last unless $foo.defined;
        $foo++;
        $count++
    }
    return $count;
}
say count-a; # Outputs 3, the correct number of "a"s in "banana"

内容的提问来源于stack exchange,提问作者Clint

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:10:49