Reputation: 770
If I have a list of lists, say [[1,2,3],[1,2,3],[1,2,3]]
, is there any way in Haskell to turn this into just 1 list, like [1,2,3,1,2,3,1,2,3]
?
Thanks in advance!
Upvotes: 10
Views: 23783
Reputation: 32455
Concat does what you'd like:
concat [[1,2,3],[1,2,3],[1,2,3]]
To find these sorts of functions in the future, you can use hoogle http://www.haskell.org/hoogle/
You can search for a type - your required function is [[Int]] -> [Int]
, so you could do this search. The top function is concat.
I should mention that in fact
concat :: [[a]] -> [a]
So it works on any list of lists, and you could also quite happily search hoogle with that type instead. Hoogle's smart enough to understand which types are appropriately close to what you asked for, though.
Upvotes: 32
Reputation: 10541
There are some ways to do it, you can use list comprehensions, for example:
[y | x <- [[1,2,3],[1,2,3],[1,2,3]], y <- x]
or join function, that, actually, same way:
import Control.Monad (join)
join [[1,2,3],[1,2,3],[1,2,3]]
or concat function:
concat [[1,2,3],[1,2,3],[1,2,3]]
or msum (same with concat):
import Control.Monad (msum)
msum [[1,2,3],[1,2,3],[1,2,3]]
or mconcat (same with concat):
import Data.Monoid (mconcat)
mconcat [[1,2,3],[1,2,3],[1,2,3]]
Upvotes: 8