简体   繁体   中英

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. 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]

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]

You cant create a list with different depth in haskell. It won't t typecheck. [[a]] are not the same type as [[[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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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