一个主要问题是你将它存储在一个数组中,当然它会保留它的所有值。
下一个问题有点微妙,dotty sequence generator syntax <i>LIST</i>, <i>CODE</i> ... <i>END</i> 不知道 CODE 部分会要求多少以前的值,所以它保留了所有这些值.
(它可以查看 CODE 的数量/数量,但目前似乎不是来自 REPL 的实验)
还有一个问题是,在 Seq 上使用 &postcircumfix:<[ ]> 会调用 .cache,假设您将在某个时候要求另一个值。
(从查看 Seq.AT-POS 的来源)
未来的实现可能会更好地解决这些缺点。
您可以使用不同的功能来创建序列,以绕过 dotty 序列生成器语法的当前限制。
sub fibonacci-seq (){
gather {
take my $a = 0;
take my $b = 1;
loop {
take my $c = $a + $b;
$a = $b;
$b = $c;
}
}.lazy
}
如果您只是遍历值,则可以按原样使用它。
my $v;
for fibonacci-seq() {
if $_ > 1000 {
$v = $_;
last;
}
}
say $v;
my $count = 100000;
for fibonacci-seq() {
if $count-- <= 0 {
$v = $_;
last;
}
}
say chars $v; # 20899
您也可以直接使用Iterator。尽管在大多数情况下这不是必需的。
sub fibonacci ( UInt $n ) {
# have to get a new iterator each time this is called
my \iterator = fibonacci-seq().iterator;
for ^$n {
return Nil if iterator.pull-one =:= IterationEnd;
}
my \result = iterator.pull-one;
result =:= IterationEnd ?? Nil !! result
}
如果您有足够新的 Rakudo 版本,您可以使用 skip-at-least-pull-one。
sub fibonacci ( UInt $n ) {
# have to get a new iterator each time this is called
my \result = fibonacci-seq().iterator.skip-at-least-pull-one($n);
result =:= IterationEnd ?? Nil !! result
}
您也可以直接实现Iterator 类,将其包装在Seq 中。
(这主要是在 Rakudo 核心中编写返回序列的方法的方式)
sub fibonacci-seq2 () {
Seq.new:
class :: does Iterator {
has Int $!a = 0;
has Int $!b = 1;
method pull-one {
my $current = $!a;
my $c = $!a + $!b;
$!a = $!b;
$!b = $c;
$current;
}
# indicate that this should never be eagerly iterated
# which is recommended on infinite generators
method is-lazy ( --> True ) {}
}.new
}