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

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:

@a.=rotate(3);

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s