Move list of lists

I am trying to make a recursive function to get the transpose of a list of lists, nxp to pxn . But I can’t do it. I was able to create a function to transfer a list of 3 xn lists to nx 3 one:

 let rec drop1 list= [(match (List.nth list 0) with [] -> [] | a::b -> b); (match (List.nth list 1) with [] -> [] | a::b -> b); (match (List.nth list 2) with [] -> [] | a::b -> b);] let rec transpose list= if List.length (List.nth list 0) == 0 then [] else [(match (List.nth list 0) with [] -> 0 | a::b -> a); (match (List.nth list 1) with [] -> 0 | a::b -> a); (match (List.nth list 2) with [] -> 0 | a::b -> a)] :: transpose (drop1 list) 

But I can not generalize it. Of course, I think in the wrong direction. Is this generalizable? Is there a better solution? Please, help.

+7
ocaml
source share
2 answers
 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) 
+11
source share

I know this is an old question, but recently I had to solve it as part of an exercise that I was doing, and I came across a solution @ sepp2k, but I could not understand how it works, so I tried to come to it using myself.

This is essentially the same algorithm, but a bit more concise, since it does not destroy the list of lists. I thought I would post it here in case someone else was looking, and might find a way to express it useful:

 let rec transpose = function | [] | [] :: _ -> [] | rows -> List.map List.hd rows :: transpose (List.map List.tl rows) 
0
source share

All Articles