5

I've written a code to calculate the Fibonacci series using array variables inside the explicit generator like this:

my @fib = [0],[1],-> @a, @b {[|@a Z+ |@b]} ... Inf;
say @fib[^6];

This works as expected. But when I use scalar variables inside the same code, it works too:

my @fib_v2 = [0],[1],-> $a, $b {[|$a Z+ |$b]} ... Inf;
say @fib_v2[^6];

Could they be called scalar variables pointing to the arrays? What are they called when they are used in this manner?

Note that I've browsed the online Raku documentation but it's hard to spot that particular information i.e. if arrays can be referred using scalar variables.

1 Answer 1

8

You should say that "the scalar variables are bound to the arrays". Because that is what happens. You could think of:

-> $a, $b { say $a; say $b }("foo", "bar")

as:

{ my $a := "foo"; my $b := "bar"; say $a; say $b }

So, when you bind an array to a scalar, it is still an Array object. And calling methods on it, will just work. It may just make reading the code more difficult.

Note this is different from assigning an array to a scalar.

raku -e 'my $a := [1,2,3]; .say for $a'
1
2
3

versus:

raku -e 'my $a = [1,2,3]; .say for $a'
[1 2 3]

The for iterating logic sees the container in $a and takes that as a sign to NOT iterate over it, even though it contains an Iterable.

Note that I've browsed the online Raku documentation but it's hard to spot that particular information i.e. if arrays can be referred using scalar variables.

It basically falls out of correctly grokking the relation between containers and binding. About 4 years ago, I wrote a blog post about it: https://opensource.com/article/18/8/containers-perl-6 Please pardon the archaic naming :-)

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.