我试图做一个递归函数来获取列表的转置,从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)