Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't a Sequence get consumed when I assign it to an @var?

Tags:

raku

According to the class Seq docs:

A Seq is born in a state where iterating it will consume the values.
...
...
A Seq can also be constructed with the sequence operator ... or one of its variants. Assigning the values of a Seq to an array consumes a Seq that is not lazy.

Extending the example in the docs:

use v6.d;

my $s = (1...5);
say $s;              # OUTPUT: «(1 2 3 4 5)␤» 
say $s.^name;        # OUTPUT: «Seq␤»

# My code:

say '-' x 10;

my @x = $s;
say @x;
say @x.^name;
say @x.elems;

say '-' x 10;

my @y = $s;
say @y;
say @y.^name;
say @y.elems;

--output:--
(1 2 3 4 5)
Seq
----------
[(1 2 3 4 5)]
Array
1
----------
[(1 2 3 4 5)]
Array
1

I expected the assignment:

my @x = $s;

to iterate over the Seq $s and consume $s during the assignment to @x. And, I expected there to be 5 elements in @x. But the output doesn't show that the Seq $s is being iterated over or consumed.

$s.is-lazy  #False

The docs seem warn you that a Seq will get iterated over when you might not expect it, and then the Seq will be consumed and the next attempt to iterate over the Seq will cause errors. But, I seem to have the opposite problem: I can't make a Seq get consumed.

like image 988
7stud Avatar asked Nov 15 '25 07:11

7stud


1 Answers

Only a partial answer (so far):

It looks like all your assignments above into an @array go into the [0]th position of the array. Note how your elems above equals 1 one.

To assign each list element to each position of the array, you have to call .list on it (pretty sure .List and .Array will give you the same results), below:

my $t = (1...5);
my @z = $t.list;
say @z;
say @z.^name;
say @z.elems;
say "\nIterate:";
.say for @z;

#OUTPUT:

[1 2 3 4 5]
Array
5

Iterate:
1
2
3
4
5

(Maybe the remainder of the answer, below):

Why don't your assignments of $s above consume the Seq? Possibly because Raku thinks you've only consumed them as one element and have not iterated through the elements of $s individually.

Really, really, guessing here, but if after assigning $t.list to @z above, if I try to call .say for $t I get the following error:

#Add to previous `$t` code (at bottom):

.say for $t;

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 block <unit> at - line 45

HTH.

like image 75
jubilatious1 Avatar answered Nov 17 '25 22:11

jubilatious1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!