ðŸ“˜ How to transpose a matrix in Perl 6

# ðŸ“˜ How to transpose a matrix in Raku

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

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)]`