Reputation: 83
I have a list of numbers eg [3,1,3]
using this list of numbers I want to partition another list. For example [1,2,3,4,5,6,7]
would become [[1,2,3],[4],[5,6,7]]
using the [3,1,3]
list. I know there is a function in the split package called chunksOf
that could do this but I want to be able to do this without it. Would splitAt
be useful in this situation?If so, how could I implement it?
Upvotes: 1
Views: 294
Reputation: 11628
Let's call this function chunkify
. This function takes two arguments, the list of values and the list of the lengths of the chunks, so it has the signature
chunkify:: [a] -> [Int] -> [[a]]
Furthermore if the first list or the second list is empty, the result must be empty too:
chunkify [] _ = []
chunkify _ [] = []
Now you already found splitAt
which does what you want but only once. So if we have a list x
and some length l
we can split off a chunk with
(chunk, remainder) = splitAt l x
But now we need to make a list of these and repeat this with the remainder
.
One way of doing so would be recursively defining a list:
chunkify x (l:ls) = chunk: chunkify remainder ls
where (chunk, remainder) = splitAt l x
Now as an exercise you could try to solve this problem using a higher order function like scanr,scanl,foldl,foldr
to avoid the explicit recursion.
Upvotes: 2