This matrix transposition function works, but I\'m trying to understand its step by step execurtion and I don\'t get it.
transpose:: [[a]]->[[a]]
tran
ghci
is your friend:
*Main> :t map head map head :: [[a]] -> [a] *Main> :t map tail map tail :: [[a]] -> [[a]]
Even if you don't understand map (a problem you'd want to correct quickly!), the types of these expressions tell much about how they work. The first is a single list taken from a list of lists, so let's feed a simple vector to it to see what happens.
You might want to write
*Main> map head [1,2,3]
but that fails to typecheck:
:1:14: No instance for (Num [a]) arising from the literal `3' at :1:14 Possible fix: add an instance declaration for (Num [a]) In the expression: 3 In the second argument of `map', namely `[1, 2, 3]' In the expression: map head [1, 2, 3]
Remember, the argument's type is a list of lists, so
*Main> map head [[1,2,3]]
[1]
Getting a bit more complex
*Main> map head [[1,2,3],[4,5,6]]
[1,4]
Doing the same but with tail instead of head gives
*Main> map tail [[1,2,3],[4,5,6]]
[[2,3],[5,6]]
As you can see, the definition of transpose
is repeatedly slicing off the first “row” with map head x
and transposing the rest, which is map tail x
.