Transposing Rows

In our last article we explored how groupBy could allow us to arrange a Matrix (represented as an Array) into its rows.

myArray :: Array (Int, Int) Double)
myArray = listArray ((0, 0), (1, 1)) [1..4]

rows = groupBy (\((a, _), _) ((b, _), _) -> a == b) (assocs myArray)

...

>> rows myArray = [[((0, 0), 1), ((0, 1), 2)], [((1, 0), 3), ((1, 1), 4)]]

But what about a different case? Suppose we were most concerned about grouping the columns together? At first glance, it doesn't seem as though this would be possible using groupBy, since the elements we want aren't actually next to each other in the assocs list.

However, there is another simple list function we can use to complete this process. The transpose function takes a list of lists, which we can think of as a "matrix". Then it transposes the matrix so that the rows are now the columns.

transpose :: [[a]] -> [[a]]

...

>> transpose [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Clearly we could use this function to achieve the result we want with our 2D array!

>> rows = groupBy (\((a, _), _) ((b, _), _) -> a == b) (assocs myArray)
>> transpose (rows myArray)
[[((0, 0), 1), ((1, 0), 3)], [((0, 1), 2), ((1, 1), 4)]]

This function, of course, works even if the input is not a "square" matrix.

>> transpose [[1, 2, 3, 4], [5, 6, 7, 8]]
[[1, 5], [2, 6], [3, 7], [4, 8]]

It even works if it is not rectangular! If some "rows" are shorter than others, than our result is still sound! Essentially, the first row in the result is "every first element of a list". The second row is every "second" element. And so on. Every element in the original list is represented in the final list. Nothing is dropped like you might have in zip.

>> transpose [[1, 2, 3], [4], [5, 6], [], [7, 8, 9, 10]]
[[1, 4, 5, 7], [2, 6, 8], [3, 9], [10]]

Hopefully this is an interesting function that you hadn't thought of using before! If you want to keep seeing tricks like this, subscribe to our monthly newsletter so you can keep up to date with the different tricks we're exploring here. You'll also get access to our subscriber resources!

Previous
Previous

Changing and Re-Arranging

Next
Next

"Group" Theory