[英]operation on list of lists | how
When I've seen concat function in Haskell book, I wonder how I can flatten the list below in Haskell. 当我在Haskell书中看到concat函数时,我想知道如何在Haskell中展平下面的列表。 In Python, I can do that because I can check its type in function. 在Python中,我可以这样做,因为我可以在函数中检查它的类型。 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]
As already pointed out, you can't have arbitrary nested lists in Haskell. 正如已经指出的那样,你不能在Haskell中拥有任意嵌套列表。 The closest thing (without dirty type class hacks using fancy pragmas) would be something like: 最接近的东西(没有使用花式pragma的脏类型hacks)将是这样的:
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]
You cant create a list with different depth in haskell. 你不能在haskell中创建一个具有不同深度的列表。 It won't t typecheck. 它不会发生变形。 [[a]]
are not the same type as [[[a]]]
. [[a]]
与[[[a]]]
。 This function will solve your question but only on list with the same depth. 此功能将解决您的问题,但仅限于具有相同深度的列表。
flat::[[a]] -> [a]
flat [] = []
flat l:ls = l ++ flat ls
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.