列表列表的转置
我正在尝试创建一个递归函数来获取列表列表的转置,从 nx p
到 px n
。但我无法这样做。我已经能够创建一个函数,将 3 x n
列表转置为 nx 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)
但我无法概括它。我肯定是在思考错误的方向。这可以概括吗?有更好的解决方案吗?请帮忙。
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 a function to transpose a 3 x n
list of lists to an n x 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'm not able to generalize it. I'm surely thinking in the wrong direction. Is this generalizable? Is there a better solution? Please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
利用自首次发布答案以来的语法更改:
Taking advantage of syntax changes since answer first posted:
我知道这是一个老问题,但我最近必须解决这个问题,作为我正在进行的练习的一部分,我遇到了 @sepp2k 的解决方案,但我无法理解它是如何工作的,所以我尝试通过我。
这本质上是相同的算法,但更简洁一些,因为它不会破坏列表的列表。我想我会将其发布在这里,以防其他人正在搜索,并且可能会发现这种表达方式很有用:
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:
假设矩阵是矩形的(否则将引发
Invalid_argument "map2"
):请注意,
map (fun _ -> []) (hd m)
只是创建一个列表空列表,长度等于m
中的列数。所以这段代码的更清晰的表示是:
Assuming the matrix is rectangular (otherwise
Invalid_argument "map2"
will be raised):Note that
map (fun _ -> []) (hd m)
just creates a list of empty lists, of length equal to the number of columns inm
.So a clearer representation of this code would be: