Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define the 'AT-POS' method?

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.
like image 273
lovetomato Avatar asked Feb 14 '19 08:02

lovetomato


1 Answers

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.

like image 133
Elizabeth Mattijsen Avatar answered Sep 29 '22 15:09

Elizabeth Mattijsen