我试图做一个递归函数来获取一个列表的列表的转置n x p
到p x n
.但我无法这样做.我已经能够创建一个函数来将3 x n
列表列表转换为一个列表n x 3
:
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)
但我无法概括它.我肯定在想错误的方向.这可以推广吗?有更好的解决方案吗?请帮忙.
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)