operator-overloading - 如何定义 'AT-POS'方法?

标签 operator-overloading raku

我定义了 AT-POS类的方法并导出 []运算符(operator)。
当我使用 []但是,在该类的实例上,编译器忽略了我定义的运算符。

这是代码:

unit module somelib;

class SomeClass is export {
    method AT-POS(@indices) {
        say "indices are {@indices.perl}"
    }
}

multi postcircumfix:<[ ]> (SomeClass:D $inst, *@indices) is export {
    $inst.AT-POS(@indices)
}
#! /usr/bin/env perl6

use v6.c
use lib ".";
use somelib;

my $inst = SomeClass.new;

$inst[3, 'hi'];

# expected output:
#   indices are 3, 'hi'

# actual output:
#   Type check failed in binding to parameter '@indices';
#   expected Positional but got Int (3)
#     in method AT-POS at xxx/somelib.pm6 (somelib) line 4
#     in block <unit> at ./client.pl6 line 8

那么这段代码有什么问题呢?

更新:

我确实需要将多个索引传递给 AT-POS 方法而且我很惊讶地发现使用 *$indices 而不是 *@indices 在我修正错字时给出了预期的输出。我不知道是否存在像 *$some-parameter 这样的用法。它是有效的还是只是编译器的错误?
unit module somelib;

class SomeClass is export {
    method AT-POS($indices) {
        say "indices are {$indices.perl}"
    }
}

multi postcircumfix:<[ ]> (SomeClass:D $inst, *$indices) is export {
    $inst.AT-POS($indices)
}
#! /usr/bin/env perl6

use v6.c;
use lib ".";
use somelib;

my $inst = SomeClass.new;

$inst[3, 'hi'];

# expected output:
#   indices are 3, 'hi' # or something like it 

# actual output:
#   indices are $(3, "hi") # It's ok for me.

最佳答案

问题是AT-POS预计仅接收一维 Positional 的单个参数.如果您指定一个切片,则该设置将负责调用 AT-POS多次并将结果收集到列表中:

class A {
    method AT-POS($a) { 2 * $a }
}
dd A.new[1,2,3,4];  # (2,4,6,8)

此外,您不需要提供 postcircumfix:<[ ]>候选人,除非你真的想做非常特别的事情:提供的设置将派往右边 AT-POS为你自动。

关于operator-overloading - 如何定义 'AT-POS'方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54685935/

相关文章:

string - Raku:从字符串中捕获组的一行表达式?

testing - 以不同顺序执行时测试失败

c++ - 继承类的运算符重载

raku - 在 Perl 6 中,如何复制 Perl 的 List::Util::all 的行为?

c++ - 自定义 C++ 类上的错误

c++ - 运算符重载困惑

regex - 在匹配中使用时如何使子规则/正则表达式不区分大小写?

raku - 为什么 Perl6 序列上没有 "each"方法?

c++ - 使用类特定的 set_new_handler

operator-overloading - Dart ,重载 [] 运算符?