πŸ“˜ 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.

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

Print the given list in reverse order.

Start with an array of integer numbers.

my @a = (10, 20, 30, 40, 50);

To reverse the array, call the reversemethod on it.

say @a.reverse;

This line prints the required result:

(50 40 30 20 10)

Notice that the initial array stays unchanged. The reversemethod creates a new sequence and returns it.

The same method works with other types of data that can be converted to a sequence, for example, ranges.

Print a range in reversed order:

my $range = 10..15;
say $range;
say $range.reverse;

Again, the original range is not changed, and the returned value is not a range but a sequence. Compare the results of printing an original value ofΒ $range with what theΒ reverse method returns:

10..15
(15 14 13 12 11 10)

πŸ“˜ Swap two values in Perl 6

Swap the values of two variables.

In Perl 6, there is no need to use temporary variables to swap the values of two variables. Just use the lists on both sides of the equation:

($b, $a) = ($a, $b);

Alternatively, call theΒ reverse method and assign the result back to the values:

($a, $b).=reverse;

Consider the complete program:

my ($a, $b) = (10, 20);
($b, $a) = ($a, $b);
say "\$a = $a, \$b = $b";

This program prints the swapped values:

$a = 20, $b = 10

This approach also works with elements of an array:

my @a = (3, 5, 7, 4);
(@a[2], @a[3]) = (@a[3], @a[2]);
say @a; # [3 5 4 7]

A slice of an array may be used instead of an explicit list:

my @a = (3, 5, 7, 4);
@a[1, 2] = @a[2, 1];
say @a; # [3 7 5 4]