user1670032
user1670032

Reputation: 770

haskell - turning list of lists into one list

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

Answers (3)

AndrewC
AndrewC

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

Fedor Gogolev
Fedor Gogolev

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

Satvik
Satvik

Reputation: 11208

Direct Answer

> concat [[1,2,3],[1,2,3],[1,2,3]]
[1,2,3,1,2,3,1,2,3]

You should try hoogle whenever you want to search for any function. Sometimes type is enough to get information about a function you need.

Upvotes: 5

Related Questions