📘 How to transpose a matrix in Perl 6

Take a matrix and print its transposed version.

A matrix can be represented by nested arrays or lists. For example, here’s a square 2×2 matrix:

my @matrix = [1, 2],
             [3, 4];

This is how the transposed matrix should look:

[[1, 3],
[2, 4]]

Actually, the outer pair of square brackets, could be added to the initializer of the @matrix variable. Perl 6 simply converts the list ([1, 2], [3, 4])  to an array when assigning it to an array variable @matrix.

Transposing a matrix is extremely easy:

my @transposed = [Z] @matrix;

The [Z] operator is a reduction form of the zip operator. For the given small matrix, it’s action is equivalent to the following code:

my @transposed = [1, 2] Z [3, 4];

Despite the simplicity of the method, it works well with bigger matrices as well as non-square ones.

For the example @matrix in this task, the output of the program is the following:

[(1 3) (2 4)]

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