Grouping a list into lists of n elements in Haskell

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.

enter image description here

Leave a Comment