Can't figure out why the pattern matching isn't working! I'm beginning with Hasklell, so be patient!
-- matrix implemented as a list of lists (rows of the matrix)
test_matrix3 = [[1,0,0],[2,-3,0],[4,5,6]]
-- transpose of a given matrix
transpose (x:[]) = [x]
transpose all@(x:_) = map head all : transpose ([tail y | y <- all])
Executing:
*Main> transpose test_matrix3
[[1,2,4],[0,-3,5],[0,0,6],[*** Exception: Prelude.head: empty list
transpose [[1,0,0],[2,-3,0],[4,5,6]]
= [1,2,4] : transpose [[0,0],[-3,0],[5,6]]
= [1,2,4] : [0,-3,5] : transpose [[0],[0],[6]]
= [1,2,4] : [0,-3,5] : [0,0,0] : transpose [[],[],[]]
And here is where it happens. This does not match the first pattern, because it is not a singleton list -- it is a list with three elements. So:
= [1,2,3] : [0,-3,5] : [0,0,0] : map head [[],[],[]] : transpose (map tail [[],[],[]])
Which will give you one error for each empty list, since neither head nor tail are defined on empty lists.
This one worked for me:
transpose' ([]:_) = []
transpose' xs = (map head xs) : (transpose' (map tail xs))
Test:
*Main> transpose' test_matrix3
[[1,2,4],[0,-3,5],[0,0,6]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With