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

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

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

这是代码:

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.
operator-overloading perl6
1个回答
11
投票

问题是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

© www.soinside.com 2019 - 2024. All rights reserved.