๐Ÿ“˜ How to rotate a list in Perl 6

๐Ÿ“˜ How to rotate a list in Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.

Move all elements of an array N positions to the left or to the right.

Array is a data type in Perl 6 that offers theย rotate method, which does exactly what is needed. It takes an argument that tells the length and direction of the rotation.

my @a = (1, 3, 5, 7, 9, 11, 13, 15);

say @a.rotate(3);
say @a.rotate(-3);

Positive values rotate to the left; negative values rotate to the right. Elements that go beyond the array borders, are appended to the end (or to the beginning if rotating to the right). 

The original array stays untouched. The program prints the following:

[7 9 11 13 15 1 3 5]
[11 13 15 1 3 5 7 9]

To modify the array, assign the result of rotation to the variable itself:


Alternatively, a pair ofย shift andย push methods can lead to the same result:

@a.push(@a.shift) for 1..3;

Rotating to the opposite side can be done using complementary methods:

@a.unshift(@a.pop) for 1..3;

In the last three examples,ย @a is updated after the operations.

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code