Alex Rivera | Logout

Is there a function to flatten a nested list of elements?

Asked 2011-05-13T15:16:09.487
64

How can I flatten a nested list like this:

[1, 2, 3, 4] == flatten [[[1,2],[3]],[[4]]]
Edit
Report

2 Answers

14

As others have pointed out, concat :: [[a]] -> [a] is the function you are looking for, and it can't flatten nested lists of arbitrary depth. You need to call it multiple times to flatten it down to the desired level.

The operation does generalize to other monads, though. It is then known as join, and has the type Monad m => m (m a) -> m a.

Prelude Control.Monad> join [[1, 2], [3, 4]]
[1,2,3,4]    
Prelude Control.Monad> join (Just (Just 3))
Just 3
Prelude Control.Monad.Reader> join (+) 21
42
answered 2011-05-13T15:39:44.487
8

As hammar pointed out, join is the "monadic" way to flatten a list. You can use the do-Notation as well to write easily flatten functions of several levels:

flatten xsss = do xss <- xsss
                  xs <- xss
                  x <- xs
                  return x
answered 2011-05-13T18:45:38.767

Your Answer