Raku 签名 (Array @r) 不是 (Array:D)?

FyF*_*AIR 9 polymorphism raku

我似乎无法弄清楚我在探索语法时发现的这个 Raku 错误消息......


Cannot resolve caller report(Array:D); none of these signatures matches:
(Array @r)
(Match $r)
Run Code Online (Sandbox Code Playgroud)

那么数组不是数组?!这是如何运作的以及我如何找出原因?这是完整的程序和输出。

#!/usr/bin/env perl6
use v6;
grammar Integers {
    rule TOP      { ^ .*? <targets> .* $  }
    rule targets  { <integer>+ % ',' }
    token integer { \d+ }
}

multi sub report(Array @r) { say @r.raku }
multi sub report(Match $r) { say $r.raku }

sub MAIN() {
    my $result = Integers.parse(' a 1234 ');
    report($result);
    report(%$result{'targets'});
    report(%$result{'targets'}{'integer'});
}
#`( output:
Match.new(:orig(" a 1234 "), :from(0), :pos(8), :hash(Map.new((:targets(Match.new(:orig(" a 1234 "), :from(3), :pos(8), :hash(Map.new((:integer([Match.new(:orig(" a 1234 "), :from(3), :pos(7))]))))))))))
Match.new(:orig(" a 1234 "), :from(3), :pos(8), :hash(Map.new((:integer([Match.new(:orig(" a 1234 "), :from(3), :pos(7))])))))
Cannot resolve caller report(Array:D); none of these signatures matches:
    (Array @r)
    (Match $r)
  in sub MAIN at /home/hans/Programming/Raku/Parsing/Array_Array.raku line 16
  in block <unit> at /home/hans/Programming/Raku/Parsing/Array_Array.raku line 3
)
Run Code Online (Sandbox Code Playgroud)

Eli*_*sen 8

您似乎对印记和打字的功能感到困惑。

当你使用@印记时,你就暗示了一种Positional约束。

sub foo(@a) { ... }
Run Code Online (Sandbox Code Playgroud)

会采取任何能发挥Positional作用的东西。

foo( @b );
foo( [1,2,3] );
foo( (1,2,3) );
Run Code Online (Sandbox Code Playgroud)

当您在签名中指定带有 a 的类型时@,表示您希望 aPositional只接受类型作为其元素。现在,作为子例程的参数,这严重限制了您可以指定的内容,因为它不是[1,2,3]一个带有约束的数组,而是一个恰好仅填充值的数组。IntInt

现在回到你的例子:这是什么(Array @r)意思?这意味着您想要一个Positional对对象进行约束的Array对象。简单来说:您想要一个必须由数组作为其元素组成的数组。

我不认为这就是你的意图?

现在,为什么(Array $r)有效?Array因为这表明您想要一个作为参数的对象。这也限制了你想要的,因为它必须是一个Array, 而不能是一个List实例。

sub foo(Array $r) { ... }
foo(@a);         # works
foo( [1,2,3] );  # works
foo( (1,2,3) );  # does *not* work
Run Code Online (Sandbox Code Playgroud)

最后,我认为您想使用内置函数dd而不是构建自己的report函数。

  • 那么 `(Array @r)` 可以被描述为数组 r 的数组,或者是 `Positional`sr 的数组?至于为什么我要重新实现 dd,这就是我学习访问 Match 对象属性的语法的方式。 (2认同)