Understanding this matrix transposition function in Haskell

前端 未结 3 2044
伪装坚强ぢ
伪装坚强ぢ 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

    The cons operator : attach an object of type a to a list of type [a]. In

    (map head x) : transpose (map tail x)
    

    The LHS is a list (a = [b]), while the RHS is a list of list ([a] = [[b]]), so such a construction is valid. The result is

    [x,y,z,...] : [[a,b,...],[d,e,...],...] = [[x,y,z,...], [a,b,...],[d,e,...],...]
    

    In your case, map head x and map tail x splits the matrix

    x = [[1,2,3],[4,5,6],[7,8,9]]
    

    into

    map head x = [1,4,7]
    map tail x = [[2,3],[5,6],[8,9]]
    

    (and yes, map head x is a list of the head elements of each list.) The 2nd part is transposed (for detail steps see @sepp2k's answer) to form

    transpose (map tail x) = [[2,5,8],[3,6,9]]
    

    so cons-ing [1,4,7] to this gives

    map head x : transpose (map tail x) =  [1,4,7] : [[2,5,8],[3,6,9]]
                                        = [[1,4,7] ,  [2,5,8],[3,6,9]]
    

提交回复
热议问题