Work in a list of lists | as

When I saw the concat function in a Haskell book, I was wondering how I can flatten the list below in Haskell. In Python, I can do this because I can check its type in a function. But in Haskell, I could not. 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]
+2
source share
2 answers

As already stated, you cannot have arbitrary nested lists in Haskell. The closest thing (without dirty hack types 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]
+6
source

You cannot create a list with different depths in haskell. This is not a typecheck. [[a]]not a type [[[a]]]. This function will solve your question, but only in the list with the same depth.

flat::[[a]] -> [a]
flat [] = []
flat l:ls = l ++ flat ls 
+4
source

All Articles