Haskell - Combining List Elements - 3 at time

Viewed 69

So... I have a list like this

[[1,2,3], [4,5,6], [7,8,9], [10,11,12], [13,14,15], [16,17,18], [20,21,22], [23,24,25], [26,27,28]]

And I would like this list to turn into this:

[[1,2,3,4,5,6,7,8,9], [10,11,12,13,14,15,16,17,18], [19,20,21,22,23,24,25,26,27]]

I've been stuck with it for hours. Is there a simple way to do this in Haskell? The only restriction is that I can only use prelude functions.

What I tried to do: Concatenate into a single giant list, then used "take 9" and got the first 9 elements, however, I dont know how to go further to the 9-18 elements and so on.

Oh, one thing I forgot to mention, don't know if it helps, but I've had some code before this, so it's guaranteed that the list is always going to be a multiple of 9.

1 Answers

You can take three sublists with pattern matching and concatenate the first three, and recurse on the second item of the 2-tuple. This thus looks like:

split3 :: [[a]] -> [[a]]
split3 (xa:xb:xc:xs) = … : split3 …
split3 ls = ls

where you need to fill in the two … parts. The first one deals with the head of the output, whereas the second makes a recursive call on the tail of the given list.

Related