gpt4 book ai didi

list - 首先查找所有列表,然后查找所有第二个,然后查找所有第三个等等。列表中的列表元素

转载 作者:行者123 更新时间:2023-12-05 00:15:40 24 4
gpt4 key购买 nike

使用 (9x9) 矩阵的自制定义,描述为 Maybe Int 的列表列表s。我想创建一个返回矩阵 9 列的函数。我想做这样的事情:

cols :: Matrix a -> [Block a]
cols matrix = map (!! n) matrix
where
n = (the values 1 .. 9)
  • 矩阵被描述为 [Rows][[values]]
  • 块被描述为 [a]

  • 所以我希望输出是一个列表列表,其中这些列表是行的第一个元素、行的第二个元素等的列表。

    我看到
    map (!! 1) matrix

    将返回行的第二个元素的列表,即矩阵的第二列;但我不知道如何在一个很好的函数中将其扩展到矩阵的所有列。

    最佳答案

    I see that


    map (!! 1) matrix

    Will return a list of the second elements of the rows, ie the second column of the matrix; but I don't know how to extend this to all the columns of the matrix in a nice function.



    如果这是您想要的方式,您可以简单地将其更改为
    map (!!i) matrix


    [map (!!i) matrix | i <- [0.. length (matrix!!0) - 1]]

    例如
    Prelude> let matrix = [[1,2,3],[4,5,6]]
    Prelude> [map (!!i) matrix | i <- [0.. length (matrix!!0) - 1]]
    [[1,4],[2,5],[3,6]]

    当然,这样做的问题是复杂度不必要地高,如 !! 的复杂度。其论证是线性的。相反,您可以构建一个递归函数,如下所示:
  • 假设您将矩阵的每个元素拆分为 headtail ,分别
  • 哪里有head转置矩阵中的所有拟合元素?
  • 如果您现在在 tail 上尝试相同的操作会发生什么所有元素?
  • 关于list - 首先查找所有列表,然后查找所有第二个,然后查找所有第三个等等。列表中的列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44016508/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com