Understanding this matrix transposition function in Haskell

前端 未结 3 2063
伪装坚强ぢ
伪装坚强ぢ 2021-02-12 06:43

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         


        
3条回答
  •  自闭症患者
    2021-02-12 07:36

    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.

提交回复
热议问题