以 the example in the Iterable doc page 开头
role DNA does Iterable {
method iterator(){ self.comb.iterator }
};
my @a does DNA = 'GAATCC';
.say for @a; # OUTPUT: «GAATCC»
我发现它使用 @
声明很奇怪,所以我将其更改为声明字符串的自然方式,$
:
my $a does DNA = 'GAATCC';
但是失败了,并出现了令人困惑的“无法分配给不可变值”。不需要当场分配,所以我们可以这样做:
my $a = 'GAATCC';
$a does DNA;
.say for $a;
这只是将混合留到以后进行。但这只是打印字符串,而不关注 Iterable mixin。让我们明确地调用它:
.say for $a.iterator;
它的作用和以前一样,只是打印 $a.iterator
的值,而不实际调用该函数:
<anon|69>.new
这看起来像 the same thing it's going on in this other question 。基本问题是我不明白 Iterable 真正的作用,以及 for
真正的作用以及它何时在某个对象上调用 iterator
。有什么想法吗?
最佳答案
我认为这条线的作用并不像你想象的那样:
my @a does DNA = 'GAATCC';
它与:
相同my @a := [ 'GAATCC', ];
@a does DNA;
基本上,.comb
调用将数组强制转换为 Str,并将其拆分为字符。
如果您这样做:
my @a = 'GAATCC' but DNA;
与此基本相同
my @a := Seq.new(('GAATCC' but DNA).iterator).Array;
请注意,@
变量存储的是Positional
值,而不是Iterable
值。
你想要的是
my $a = 'GAATCC' but DNA;
$a.map: &say;
<小时/>
如果您希望能够使用 for
,则不能使用带有 $
符号的变量
my \a = 'GAATCC' but DNA;
.say for a;
<小时/>
您可能需要向 DNA
添加 Seq
list
List
等方法。
role DNA does Iterable {
method iterator(){
self.comb.iterator
}
method Seq(){
Seq.new: self.iterator
}
method list(){
# self.Seq.list
List.from-iterator: self.iterator
}
}
my $a = 'GAATCC' but DNA;
.say for @$a;
关于iterator - "Cannot assign to immutable value"尝试分配给字符串+角色时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50590224/