Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten a list of lists

I have to write a function that flattens a list of lists.

For example flatten [] = [] or flatten [1,2,3,4] = [1,2,3,4] or flatten [[1,2],[3],4,5]] = [1,2,3,4,5]

I'm having trouble with the being able to match the type depending on what is given to the flatten function.

Here's what I have:

data A a = B a | C [a] deriving (Show, Eq, Ord)

flatten::(Show a, Eq a, Ord a)=>A a -> A a
flatten (C []) = (C [])
flatten (C (x:xs) ) = (C flatten x) ++ (C flatten xs)
flatten (B a) = (C [a])

From what I can tell the issue is that the ++ operator is expecting a list for both of its arguments and I'm trying to give it something of type A. I've added the A type so the function can either get a single element or a list of elements.

Does anyone know a different way to do this differently, or explain what I can do to fix the type error?

like image 641
captainpirate Avatar asked Feb 29 '12 22:02

captainpirate


People also ask

What does it mean to flatten a list?

Flattening lists means converting a multidimensional or nested list into a one-dimensional list. For example, the process of converting this [[1,2], [3,4]] list to [1,2,3,4] is called flattening.

How do you flatten a nested array in Python?

To flatten a list of lists in Python, use the numpy library, concatenate(), and flat() function. Numpy offers common operations, including concatenating regular 2D arrays row-wise or column-wise. We also use the flat attribute to get a 1D iterator over the array to achieve our goal.


2 Answers

It's a bit unclear what you are asking for, but flattening a list of list is a standard function called concat in the prelude with type signature [[a]] -> [a].

If you make a data type of nested lists as you have started above, maybe you want to adjust your data type to something like this:

 data Lists a = List [a] | ListOfLists [Lists a]

Then you can flatten these to a list;

 flatten :: Lists a -> [a]
 flatten (List xs) = xs
 flatten (ListOfLists xss) = concatMap flatten xss

As a test,

 > flatten (ListOfLists [List [1,2],List [3],ListOfLists [List [4],List[5]]])
 [1,2,3,4,5]
like image 189
Malin Avatar answered Nov 03 '22 23:11

Malin


Flatten via list comprehension.

flatten arr = [y | x<- arr, y <- x]
like image 35
windmaomao Avatar answered Nov 03 '22 22:11

windmaomao