简体   繁体   English

Haskell - 映射列表列表

[英]Haskell - mapping over a list of lists

I've been trying to get a list of lists from a list of lists of ints for example: 我一直试图从一系列的整数列表中获取一个列表列表,例如:

[[0,0,1,4,7,10,11,12,16],[1,4,4,6,7,7,12,12,19],[0,0,0,2,4,7,11,12,13]]

should yield [[0,1,0],[0,4,0],[1,4,0] ..and so on ] 应该产生[[0,1,0],[0,4,0],[1,4,0] ..等等]

I can get [0,1,0] using 我可以使用[0,1,0]

map head saidList

And so I've been trying then to use that on the tail of the lists but I can't figure it out. 所以我一直在尝试在列表的尾部使用它,但我无法弄明白。

Any help would be hugely appreciated because this is the final and very small part of a huge project. 任何帮助都将非常受欢迎,因为这是一个巨大项目的最后和非常小的一部分。

Look into Data.List 查看Data.List

ghci> :t Data.List.transpose
Data.List.transpose :: [[a]] -> [[a]]
ghci> Data.List.transpose [[0,0,1,4,7,10,11,12,16],[1,4,4,6,7,7,12,12,19],[0,0,0,2,4,7,11,12,13]]
[[0,1,0],[0,4,0],[1,4,0],[4,6,2],[7,7,4],[10,7,7],[11,12,11],[12,12,12],[16,19,13]]

Your approach 你的方法

map head l

only produces the first list and only works if all lists in the original list of lists are not empty. 只生成第一个列表,并且只有在原始列表列表中的所有列表都不为空时才有效。

You need a way to discard empty lists (you do not want to take the head of these), and then a way to apply the same procedure to the tails of the non-null lists. 您需要一种方法来丢弃空列表(您不想占用这些列表),然后将一种方法应用于非空列表的尾部。 Here is a possible solution: 这是一个可能的解决方案:

filterNonNull x = filter (\y -> not (null y)) x

f x = if null h then [] else h : t
    where
      n = filterNonNull x
      h = (map head n)
      t = f (map tail n)

I tested it on ghci: 我在ghci上测试过它:

f [[1, 2, 3], [4, 5, 6],[7,8]]

gives

[[1,4,7],[2,5,8],[3,6]]

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

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