Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping a list into lists of n elements in Haskell

Tags:

list

haskell

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?

like image 695
1775 Avatar asked Oct 13 '12 19:10

1775


People also ask

How do you get the first N elements of a list in Haskell?

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.


1 Answers

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

like image 182
Mihai Maruseac Avatar answered Sep 19 '22 11:09

Mihai Maruseac