I'm trying to make up my mind on how to do a transpose of a matrix in Haskell using only !! and length. I have already written a function to get the column of a matrix at any given index i:
getCol :: [[Int]] -> Int -> [Int]
getCol [] i = []
getCol (xs:xss) i = if isMatrix xss then (xs !! i) : getCol xss i else []
Plus, a function to return the length of a row:
rowLength :: [[Int]] -> Int
rowLength (x:xs) = length x
My plan right now is to fill a list n times with entries of getCol, with n being the rowLength of the list I call the function on.
So, for this sample list:
list = [[1,2,3],[4,5,6],[7,8,9]]
-- rowLength ---> 3
-- then fill another list with every column of list,
-- for the indices 0..n (with n being rowLength)
-- resulting in [[1,4,7],[2,5,8],[3,6,9]
Problem is, I would normally do this with the head and tail functions, but I am only allowed to use length and !!.
My idea so far is
trav :: [[Int]] -> [[Int]]
trav xxs n = if (n <= rowLength) then getCol xxs n+1 : getCol xxs n else ?
my only issue is the else case. I know that it's mandatory in Haskell but I also know that my implementation doesn't make sense with an else case. This is my first time working with a functional language rather than an imperative one like Java, so I'm trying to somewhat simulate a loop here for the indices but don't know how to do that :(
Could anyone give me a tip? I would super appreciate that!!