gpt4 book ai didi

role - 为什么 Perl 6 Str 扮演 Positional 角色,如何更改 []?

转载 作者:行者123 更新时间:2023-12-04 22:28:25 25 4
gpt4 key购买 nike

我正在玩字符串的位置界面。我知道 How can I slice a string like Python does in Perl 6? ,但我很好奇我是否可以让这件事只为傻笑而工作。

我想出了这个例子。阅读位置很好,但我不知道如何设置multi处理任务:

multi postcircumfix:<[ ]> ( Str:D $s, Int:D $n --> Str ) {
$s.substr: $n, 1
}
multi postcircumfix:<[ ]> ( Str:D $s, Range:D $r --> Str ) {
$s.substr: $r.min, $r.max - $r.min + 1
}
multi postcircumfix:<[ ]> ( Str:D $s, List:D $i --> List ) {
map( { $s.substr: $_, 1 }, @$i ).list
}

multi postcircumfix:<[ ]> ( Str:D $s, Int:D $n, *@a --> Str ) is rw {
put "Calling rw version";
}


my $string = 'The quick, purple butterfly';

{ # Works
my $single = $string[0];
say $single;
}

{ # Works
my $substring = $string[5..9];
say $substring;
}

{ # Works
my $substring = $string[1,3,5,7];
say $substring;
}

{ # NOPE!
$string[2] = 'Perl';
say $string;
}

最后一个不起作用:
T
uick,
(h u c)
Index out of range. Is: 2, should be in 0..0
in block <unit> at substring.p6 line 36

Actually thrown at:
in block <unit> at substring.p6 line 36

不过,我不认为它会起作用。我不知道它应该有什么签名或特征来做我想做的事。

为什么 [] 运算符(operator)在 Str 上工作?
$ perl6
> "some string"[0]
some string

文档大多暗示 []适用于 Positional 的事情角色,并且这些东西在列表中。来自 [] docs in operators :

Universal interface for positional access to zero or more elements of a @container, a.k.a. "array indexing operator".



但是一个 Str令人惊讶的是,即使它不是 @container,它也扮演了必要的角色。 (据我所知):
> "some string".does( 'Positional' )
True

有没有办法测试某个东西是 @container ?

有没有办法让一些东西列出它的所有角色?

现在,知道字符串可以响应 [] ,我怎样才能知道什么签名会匹配呢?我想知道用于定义我自己的版本以通过 [] 写入此字符串的正确签名.

最佳答案

实现此目的的一种方法是增加 Str类,因为你真的只需要覆盖 AT-POS方法(Str 通常继承自 Any ):

use MONKEY;
augment class Str {
method AT-POS($a) {
self.substr($a,1);
}
}
say "abcde"[3]; # d
say "abcde"[^3]; # (a b c)

更多信息可以在这里找到: https://docs.raku.org/language/subscripts#Methods_to_implement_for_positional_subscripting

关于role - 为什么 Perl 6 Str 扮演 Positional 角色,如何更改 []?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45292437/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com