简体   繁体   English

在Haskell中访问列表中列表的第n个元素

[英]Accessing nth element of a list in list in Haskell

I am trying to build a function which works on lists of lists. 我正在尝试构建一个适用于列表列表的函数。 This function would take the 1rst element of each list inside the big list, put them into a list together, then do this for the 2nd element, etc. Ex: 这个函数将每个列表的第一个元素放在大列表中,将它们放在一个列表中,然后为第二个元素执行此操作,等等。

tr[[1,2,3],[4,5,6]]    
=> [[1,4],[2,5],[3,6]

It can work for any data type, but for now I am trying to make it work for Int 它可以适用于任何数据类型,但是现在我试图让它适用于Int

Here is what I have so far, just the data declaration and a case for empty input: 这是我到目前为止,只是数据声明和空输入的情况:

tr :: [[a]] -> [[a]]

tr [] = []

Any help is much appreciated, or even a pointer to a place with information. 非常感谢任何帮助,甚至是指向有信息的地方的指针。 My idea is that it will use the ++ operator, and the x:xs manipulation of List elements. 我的想法是它将使用++运算符和List元素的x:xs操作。 My problem is figuring out how to access the head of each list respectively, and not just the first list. 我的问题是弄清楚如何分别访问每个列表的头部,而不仅仅是第一个列表。 I can get the 1 from the example using: head $ head [[1,2,3]]. 我可以使用以下方法从示例中获取1:head $ head [[1,2,3]]。

Comments answer your question. 评论回答你的问题。 But, a more generic/abstract version would be one which works with any Foldable data structure, not only lists. 但是,更通用/抽象的版本将适用于任何Foldable数据结构,而不仅仅是列表。 That can be done with nested right folds: 这可以通过嵌套的右侧折叠来完成:

import Prelude hiding (foldr)  -- older version ghc
import Data.Foldable (foldr, Foldable)

tr :: (Foldable f, Foldable s) => f (s a) -> [[a]]
tr = takeWhile (not . null) . foldr (foldr go id) (repeat [])
  where go i f (x:xs) = (i:x): f xs

then: 然后:

\> tr [[10,11],[20],[],[30,31,32]] 
[[10,20,30],[11,31],[32]]

\> tr [Just 1, Nothing, Just 2]
[[1,2]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM