0

I have a working Haskell example of how to do it when we want to add zeros to the left and to the right of a list as two separate functions, and I did it because I considered the possibility of safe transposition by using a different definition for the latter, which I will post here as well to ask whether or not it's important to have such concerns.

rectangular :: [[Integer]] -> [[Integer]]
rectangular m = rect m []
  where
    rect [] a = ([0]:a)
    rect (l:[]) a = (l:a)
    rect (l:j:ks) a
      | length l < length j = rect ((0:l):(rect (j:ks) a)) a
      | length l > length j = rect (l:(rect ((0:j):ks) a)) a
      | otherwise           = rect (l:a) (rect (j:ks) a)

The above is to add zeros to the left, so it should be obvious how to add to the right, and the transposition definition that I'm using for this is:

transposition :: [[a]] -> [[a]]
transposition m = transpose' m []
  where
    transpose' [] a = a
    transpose' ([]:xss) a = transpose' xss a
    transpose' ((x:xs):xss) a = transpose' a ((x:map head xss): transpose' (xs:map tail xss) a)

Now that the list of lists is rectangular, transposition should work without running into empty list calls, before it's run to the end with every row having the same number of columns. Is this useful or simply redundant? These are numbers, when it could be data, so should we run the risk of adding to it? That is, in case we redefined it to accept other types, or generalized the choice between left and right.

Marco_O
  • 99
  • 1
  • 8
  • It seems to me you are dealing with matrices. Why not use [`Data.Matrix`](https://hackage.haskell.org/package/matrix-0.3.6.1/docs/Data-Matrix.html) and [`transpose :: Matrix a -> Matrix a`](https://hackage.haskell.org/package/matrix-0.3.6.1/docs/Data-Matrix.html#v:transpose)? – Micha Wiedenmann Jan 17 '22 at 12:25
  • Thanks. Perhaps I should provide a bit more context. My problem is when I'm faced with rows which don't have the same number of columns, like `[[1],[2,3],[4,5,6]]`, and the result that I want is `[[1,0,0],[2,3,0],[4,5,6]]` or `[[0,0,1],[0,2,3],[4,5,6]]`. – Marco_O Jan 17 '22 at 12:35
  • 1
    @Marco_O cf. [`padAll`](https://stackoverflow.com/a/54970785/849891)`0 [[1],[2,3],[4,5,6]]` ==> `[[1,0,0],[2,3,0],[4,5,6]]`. – Will Ness Jan 17 '22 at 20:29
  • @WillNess, thank you for linking to that `padAll` implementation, it was most useful, but I think that it's the opposite of the exercise that I was proposed with, because I could not assume the existence of `transpose`. Instead, I had to build something that allowed a naive implementation of that function to be safe, and I've corrected my code with something that was missing. I voted yours up for the generalization and hope that I'm not missing anything else. – Marco_O Apr 19 '22 at 07:32

0 Answers0