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?
There is a function in Haskell that takes first n elements of user-supplied list, named take . The syntax is: function-name arg1 arg2 . So, take takes first 1000 elements from an infinite list of numbers from 0 to infinity.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With