简体   繁体   English

如何在haskell中展平列表列表

[英]How to flatten a list of lists of lists in haskell

All I want to do is what I ask. 我想做的只是我要问的。 The type signature of the function should be this: 函数的类型签名应该是这样的:

flatten::[[[Int]]] -> [[Int]]

I tried to search some flatten code but they define new types and that confuses me. 我试图搜索一些扁平的代码,但他们定义了新类型,这让我感到困惑。 Any help? 有帮助吗? Thanks in advance. 提前致谢。

There are (at least) two ways to write 有(至少)两种写法

flatten::[[[Int]]] -> [[Int]]

One is 一个是

flatten1 = concat
-- Example: flatten [[[1], [2]], [[3]]] = [[1], [2], [3]] :: [[Int]]

Another one is 另一个是

flatten2 = map concat
-- Example: flatten [[[1], [2]], [[3]]] = [[1,2], [3]] :: [[Int]]

Basically, flatten1 flattens the "middle" level of brackets, while flatten2 flattens the "innermost" level of brackets. 基本上, flatten1使托架的“中间”水平变平,而flatten2使托架的“最里面”水平变平。

As an exercise, you might want to convince yourself that 作为练习,您可能想要说服自己

concat . flatten1 = concat . flatten2 :: [[[Int]]] -> [Int]

Indeed, both would produce [1,2,3] on the example above. 实际上,两者都会在上面的例子中产生[1,2,3]

A more advanced remark 更高级的评论

The law above is actually a very famous one, since it is a special case of the monad law 上面的法律实际上是一个非常着名的法律,因为它是monad法律的一个特例

join . fmap join = join . join :: Monad m => m (m (m a)) -> m a

where m = [] (ie, in the list monad), and a=Int 其中m = [] (即在列表monad中), a=Int

You are looking for 你在找

concat :: [[a]] -> [a]

In your use case, the element type happens to be [Int] . 在您的用例中,元素类型恰好是[Int]

One of the best ways to find answers to questions like yours is to use hoogle. 找到像你这样的问题的答案的最佳方法之一是使用hoogle。 For example see http://www.haskell.org/hoogle/?hoogle=%5B%5B%5Ba%5D%5D%5D+-%3E+%5B%5Ba%5D%5D . 例如,请参阅http://www.haskell.org/hoogle/?hoogle=%5B%5B%5Ba%5D%5D%5D+-%3E+%5B%5Ba%5D%5D

The concat function is second in the resulting list. concat函数在结果列表中排名第二。

There is also hayoo: http://holumbus.fh-wedel.de/hayoo/hayoo.html which searches all of hackage. 还有一个问题: http ://holumbus.fh-wedel.de/hayoo/hayoo.html搜索所有的hackage。

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

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