transpose of a list of lists

后端 未结 2 490
-上瘾入骨i
-上瘾入骨i 2020-12-11 17:33

I\'m trying to make a recursive function to get the transpose of a list of lists, n x p to p x n. But i\'m unable to do so. I\'ve been able to make

相关标签:
2条回答
  • 2020-12-11 18:06

    I know this is an old question, but I recently had to solve this as part of an exercise I was doing, and I came across @sepp2k's solution, but I couldn't understand how it worked, so I tried to arrive at it by myself.

    This is essentially the same algorithm, but a little bit more terse, as it does not destructure the list of lists. I thought I would post it here in case anyone else is searching, and might find this way of expressing it useful:

    let rec transpose = function
       | [] 
       | [] :: _ -> []
       | rows    -> 
           List.map List.hd rows :: transpose (List.map List.tl rows)
    
    0 讨论(0)
  • 2020-12-11 18:08
    let rec transpose list = match list with
    | []             -> []
    | []   :: xss    -> transpose xss
    | (x::xs) :: xss ->
        (x :: List.map List.hd xss) :: transpose (xs :: List.map List.tl xss)
    
    0 讨论(0)
提交回复
热议问题