将 AT-POS 实现为 return 个对象而不是事物列表

Implementing AT-POS to return an object instead of a list of things

我有以下 class:

class Names {
    has @!names;

    method add-name( $name ) { @!names.push($name) }

    multi method AT-POS( ::?CLASS:D: $index ) {
        my $new-names-obj = Names.new;

        for @!names[$index] -> $name {
            $new-names-obj.add-name($name);
        }

        return $new-names-obj;
    }

    method gist {
        @!names.join("\n")
    }
}

我希望能够切片 Names 对象和 returned 值 应该是另一个 Names 对象,其元素从 原始 Names 对象。例如:

my $original = Names.new;
$original.add-name($_) for <jonathan joseph jotaro josuke giorno>;
my $sliced-off = $original[0..2];

say $original.^name;   #=> Names
say $original;         #=> jonathan, joseph, jotaro, josuke, giorno
say $sliced-off.^name; #=> List
say $sliced-off;       #=> (jonathan joseph jotaro)

当传递单个参数时,它会按预期工作并如本 中所述,但范围并非如此,因为 AT-POS 最终被多次调用并收集结果一个列表。因此,我想知道在使用范围时是否可以 return 单个对象 $sliced-off,而不是结果列表。

AT-POS方法旨在让一个对象充当Positional对象。这不是您想要的。你想要 object[slice] DWIM。

实现该目标的最佳方法是为您的对象创建一个 postcircumfic:<[ ]>(多个)候选对象:

class A {
    method slice(@_) {
        say @_;  # just to show the principle
    }
}
sub postcircumfix:<[ ]>($object, *@indices) {
   constant &slicer = &postcircumfix:<[ ]>;
   $object ~~ A
     ?? $object.slice(@indices)
     !! slicer($object, @indices)
}

A.new[1,2,4,5];  # [1 2 4 5]

my @a = ^10;     # check if foo[] still works
say @a[1,2,4,5]; # (1 2 4 5)

为了确保 @a[] 的常见行为得以保留,我们在编译时保存系统 postcircumfix:[ ]> 的值(使用 constant)。然后在运行时,当对象不是右边的class时,用给定的参数调用postcircumfix:<[ ]>的原始版本

基于 Liz 的指导:

class Names {
    has @.names;                                      # Make public so [] can access.
    method new (*@names) { nextwith :@names }         # Positional .new constructor.
    submethod BUILD (:@!names) {}                     # Called by nextwith'd Mu new.
    multi sub postcircumfix:<[ ]>                     # Overload [] subscript.
      ( Names $n, $index, *@indices )                 # Why `$index, *@indices`?
      is default is export                            # And why `is default`?
      { Names.new: |$n.names[ |$index, |@indices ] }  # Why? See my comment 
    method gist { @!names.join(', ') }                # below Liz's answer.
}
import Names;

my $original = Names.new: <jonathan joseph jotaro josuke giorno>;
my $sliced-off = $original[0..2];

say $original.^name;   #=> Names
say $original;         #=> jonathan, joseph, jotaro, josuke, giorno
say $sliced-off.^name; #=> Names
say $sliced-off;       #=> jonathan, joseph, jotaro

PLMK 如果代码或解释不充分。