Grouping a list into lists of n elements in Haskell
haskell, list
Solution
A quick search on Hoogle showed that there is no such function. On the other hand, it was replied that there is one in the `split` package, called `chunksOf`.
However, you can do it on your own
group :: Int -> [a] -> [[a]]
group _ [] = []
group n l
| n > 0 = (take n l) : (group n (drop n l))
| otherwise = error "Negative or zero n"
Of course, some parentheses can be removed, I left there here for understanding what the code does:
The base case is simple: whenever the list is empty, simply return the empty list.
The recursive case tests first if `n` is positive. If `n` is `0` or lower we would enter an infinite loop and we don't want that. Then we split the list into two parts using `take` and `drop`: `take` gives back the first `n` elements while `drop` returns the other ones. Then, we add the first `n` elements to the list obtained by applying our function to the other elements in the original list.
Problem
Is there an operation on lists in library that makes groups of n elements? For example: n=3 ``` groupInto 3 [1,2,3,4,5,6,7,8,9] = [[1,2,3],[4,5,6],[7,8,9]] ``` If not, how do I do it?