Haskell 中以行列表形式给出的矩阵的第一列
如果我有一个矩阵作为行列表 [[1,2,3],[4,5,6]],我想返回第一列 [1,4]。 我是 Haskell 的绝对初学者,我什至不知道如何处理嵌套列表。
If I have a matrix given as a list of rows [[1,2,3],[4,5,6]], I want to return the first column, [1,4]. I'm an absolute beginner in Haskell and I have no idea on even how to deal with nested lists.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
以下代码将完成这项工作:
map
是 haskell(和其他函数式编程语言)中最有用的函数之一。 给定一个列表[a,b,c,d]
和一个函数f
,map f [a,b,c,d]
将返回列表[fa, fb, fc, fd]
。head
函数提取列表的第一个元素。 这就是为什么The following code will do the job:
map
is one of the most useful functions in haskell (and other functional programming languages). Given a list[a,b,c,d]
and a functionf
,map f [a,b,c,d]
will return the list[f a, f b, f c, f d]
. Thehead
function extracts the first element of a list. This is why更一般地说:
请记住,如果 n 大于或等于您提供的任何列表的长度,这将会失败。
More generically:
Keep in mind that this will fail if n is greater than or equal to the length of any of the lists you give it.
将行矩阵转换为列矩阵的库函数是 Data.List.transpose。 因此,解决问题的一种方法是
您还可以编写一个函数来从矩阵中获取任何列:
免责声明:
请记住,如果您需要转置整个矩阵,则转置的成本很高。 对于第一列,它的成本应该与人们给出的其他解决方案大致相同。
另外,转置在复杂的代码中相对危险,因为它的结果与其参数的类型相同:
[[a]] -> [[a]]
。 因此很容易输入错误数量的转置。 (我经过惨痛的教训才学到这个。)The library function to convert a matrix of rows to a matrix of columns is
Data.List.transpose
. So one way to solve your problem isYou could also write a function to get any column from the matrix:
Disclaimers:
Remember that transpose is expensive if you need to transpose the whole matrix. For just the first column, it should be about the same cost as the other solutions people have given.
Also, transpose is relatively dangerous in complicated code because its result is the same type as its argument:
[[a]] -> [[a]]
. So it's easy to throw in the wrong number of transposes. (I learned this the hard way.)扩展乔纳斯的答案;
map
将函数应用于列表的每个元素。 将函数“映射”到列表上的结果是不同类型的新列表。这里的输入列表的类型是
[[Int]]
,这意味着列表中的每个元素都是Int
的列表。 因此,您需要一个函数来获取每个子列表并返回其第一个元素; 那是head
。总而言之,
map
将采用函数head
,将其应用于每个子列表,以便您将获得一个[Int] 仅包含每个列表的头(第一个元素)。
To expand on Jonas' answer;
map
applies a function to each element of a list. The result of "mapping" a function over a list is a new list of a different type.The input list you have here is of type
[[Int]]
, that means, each element in the list is a list ofInt
s. So you want a function that takes each of the sublists and returns its first element; That ishead
.To sum up,
map
will take the functionhead
, apply it to each of the sublists so that you will get a new list of type[Int]
containing just the head (first element) of each list.