Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I solve "The iterator of this Seq is already in use"?

Tags:

raku

This code:

sub MAIN(Int $N = 128)
{
    my @pascal = ((1,), { (0, |@^a) Z+ (|@^a, 0) } ... *);

    my @top = @pascal[^$N];
    say "Percentage of odd numbers in the first $N rows: ",
        (100 × @top».grep(* % 2).sum / @top.sum).fmt('%.12f%%');
}

gives me an error:

The iterator of this Seq is already in use/consumed by another Seq
(you might solve this by adding .cache on usages of the Seq, or
by assigning the Seq into an array)
  in sub MAIN at ./pascal1 line 8
  in block <unit> at ./pascal1 line 1

Any idea how to solve it? I've tried adding .cache in several places, but no luck.

like image 425
mscha Avatar asked Oct 16 '20 19:10

mscha


2 Answers

The block you have as part of your sequence is creating a Seq. You should be able to cache it like this:

{ ( (0, |@^a) Z+ (|@^a, 0) ).cache }

like image 148
Daniel Mita Avatar answered Oct 16 '22 10:10

Daniel Mita


Z returns a Seq

As a Seq produces it's next value, it throws the previous one away.

So you can generally only get the values from a Seq once.

The block {…} you have works by looking at the previous Seq it generated. So there is an issue. Either you get to see what is in those Seq, or the ... operator gets to see what is in the Seq


The thing is, you probably didn't want the result of Z to be a Seq, you wanted it to be a List.

After all you start off the ... sequence generator with a List (1,).

((1,), { ((0, |@^a) Z+ (|@^a, 0)).List } ... *)
like image 40
Brad Gilbert Avatar answered Oct 16 '22 11:10

Brad Gilbert