在列表|列表上操作怎么样 [英] operation on list of lists | how
本文介绍了在列表|列表上操作怎么样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我在Haskell书中看到concat函数时,我想知道如何在Haskell中将下面的列表弄平。在Python中,我可以这样做,因为我可以在函数中检查它的类型。但是在Haskell中我不能。如何将下面的列表弄平?
When I've seen concat function in Haskell book, I wonder how I can flatten the list below in Haskell. In Python, I can do that because I can check its type in function. But in Haskell I couldn't. How can I flatten the list below?
input: [[1, 2], [[2, 3], 5], [[[2, 3], [4, 5]], [2, 3]]]
output: [1, 2, 2, 3, 5, 2, 3, 4, 5, 2, 3]
推荐答案
正如已经指出的那样,在Haskell中有任意的嵌套列表。最近的事情(没有使用奇特的编译指示的脏类型黑客)会是这样的:
As already pointed out, you can't have arbitrary nested lists in Haskell. The closest thing (without dirty type class hacks using fancy pragmas) would be something like:
data Nested a = L a | B [Nested a]
flatten :: Nested a -> [a]
flatten (L x) = [x]
flatten (B xs) = concatMap flatten xs
print $ flatten $ B[B[L 1,L 2],B[B[L 2,L 3],L 5],B[B[B[L 2,L 3],B[L 4, L 5]],B[L 2,L 3]]]
--[1,2,2,3,5,2,3,4,5,2,3]
这篇关于在列表|列表上操作怎么样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文