How to define the 'AT-POS' method?

為{幸葍}努か 提交于 2021-02-08 13:10:33

问题


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.

Here is the code:

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?

UPDATE:

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.

回答1:


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)

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.



来源:https://stackoverflow.com/questions/54685935/how-to-define-the-at-pos-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!