如何定义“AT-POS"方法? [英] How to define the 'AT-POS' method?
问题描述
我为一个类定义了 AT-POS
方法并导出了 []
操作符.但是,当我在该类的实例上使用 []
时,编译器忽略了我定义的运算符.
I defined the AT-POS
method for a class and exported the []
operator.
When I used []
on the instance of that class, however, the compiler ignored the operator defined by me.
代码如下:
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
那么这段代码有什么问题?
So what is the problem with this code?
更新:
我确实需要将多个索引传递给 AT-POS 方法而且我很惊讶地发现使用 *$indices 而不是 *@indices 在我修正一个错字时给出了预期的输出.我不知道是否存在像 *$some-parameter 这样的用法.它是有效的还是只是编译器的错误?
I did need to pass more than one indices to the AT-POS method And I was quite surprised to find that using *$indices rather than *@indices gave the expected output when I was fixing a typo. I don't know there exists such usage like *$some-parameter. Is it valid or just a bug of the compiler?
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
并将结果收集到列表中:
The problem is that AT-POS
is only expected to receive a single argument for a 1-dimensional Positional
. If you specify a slice, then the setting will take care of calling AT-POS
multiple times and collect the results into a list:
class A {
method AT-POS($a) { 2 * $a }
}
dd A.new[1,2,3,4]; # (2,4,6,8)
此外,您不需要提供 postcircumfix:<[ ]>
候选,除非您真的想做非常特殊的事情:所提供的设置将发送到右侧 AT-POS
自动为您服务.
Also, you don't need to provide a postcircumfix:<[ ]>
candidate, unless you really want to do very special things: the setting provided one will dispatch to the right AT-POS
for you automagically.
这篇关于如何定义“AT-POS"方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!