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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
splitpackage, calledchunksOf.However, you can do it on your own
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
nis positive. Ifnis0or lower we would enter an infinite loop and we don’t want that. Then we split the list into two parts usingtakeanddrop:takegives back the firstnelements whiledropreturns the other ones. Then, we add the firstnelements to the list obtained by applying our function to the other elements in the original list.