Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a variable and assign an expression to it in one step in Raku

Tags:

raku

I'm trying to use a variable and assign an expression to it in one step:

The given (sample) code

my @l=<a b c d e f g h i j k>;
my $i=0;
while $i < 7 {
    say @l[$i];
    $i= ($i+1) * 2;
}

# Output:
# a
# c
# g

The desired functionality:

my @l=<a b c d e f g h i j k>;
my $i=0;
say @l[$i =~ ($i+1) * 2] while $i < 7;
# Here, first the @l[$i] must be evaluated 
# then $i must be assigned to the expression
# ($i+1) * 2 
# (The =~ operator is selected just as an example)

# Output:
# The same output as above should come, that is:
# a
# c
# g

After the variable $i is used, the (sample) expression ($i+1) * 2 should be assigned to it in one step and that should take place solely inside the array index @l[$i =~ ($i+1) * 2] i.e. the argument of while should not be changed.

Here I took the Regex equation operator =~ (check and assign operator, AFAIK) just as an example. In this context of course, it did not work. I need to Are there any operators or some workaround to achieve that functionality? Thank you.

like image 701
Lars Malmsteen Avatar asked Nov 24 '19 12:11

Lars Malmsteen


2 Answers

You mean, something like this?

my @l = <a b c d e f g h i j k>; 
say @l[ 0, (* + 1) * 2 ...^ * > 7 ]; # says a c g;

A little bit more verbose:

my @l = <a b c d e f g h i j k>; 
say @l[ 0, -> $i { ($i + 1) * 2 } ...^ -> $i { $i > 7 } ];

Or even

my sub next-i( $i ) { ($i + 1) * 2 };
my sub last-i( $i ) { $i > 7 };

my @l = <a b c d e f g h i j k>; 
say @l[ 0, &next-i ...^ &last-i ];

Edit: Or, if as in the comment below you know the number of elements beforehand, you can get rid of the end block and (simplify?) to

say @l[ (0, (* + 1) * 2 ... *)[^3] ];

Edit:

using a variable and assigning an expression to it in one step

Well, the result of an assignment is the assigned value, if that is what you mean/want, so if you insist on using a while loop, this might work for you.

my @l = <a b c d e f g h i j k>; 
my $i = -1; say @l[ $i = ($i + 1) * 2 ] while $i < 3;
like image 105
Holli Avatar answered Sep 22 '22 10:09

Holli


my @l=<a b c d e f g h i j k>;
my $i=0;
say @l[($=$i,$i=($i+1)*2)[0]] while $i < 7'

a
c
g

A bit of cheating using $. Otherwise, it didn't work...

I would have thought ($i,$i=($i+1)*2)[0] would have done the trick.

like image 40
zengargoyle Avatar answered Sep 22 '22 10:09

zengargoyle