HiveBrain v1.2.0
Get Started
← Back to all entries
patternModerate

Split list into groups of n in Haskell

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
groupsintosplithaskelllist

Problem

I need to split a list into equal sublists, e. g [1..9] split into groups of 3 will be [[1, 2, 3], [4, 5, 6], [7, 8, 9]]. I have accomplished this task in the following way:

splitInGroupsOf n = takeWhile ((n ==) . length)
                  . map fst
                  . drop 1
                  . iterate (\(res, list) -> splitAt n list)
                  . (,) []


where iterate creates list of tuples with first n elements and rest of list. This way I had to use (,) [] on argument to ensure correct type, and unwrap result afterwards. My questions are

  • is there a better/more elegant way of performing same task?



  • is there some standard function I should make use of?



P.S.: I'm not sure where to ask simple Haskell-related questions and will appreciate if someone points me a better place for this than SE.

Solution

There are Data.List.Split.chunksOf and Data.List.Grouping.splitEvery implementations of this routine in specialized packages (and a number included in other application packages: search by Int -> [a] -> [[a]] signature on Hayoo).

I think splitEvery implementation is pretty elegant:

splitEvery :: Int -> [a] -> [[a]]
splitEvery _ [] = []
splitEvery n xs = as : splitEvery n bs 
  where (as,bs) = splitAt n xs

Code Snippets

splitEvery :: Int -> [a] -> [[a]]
splitEvery _ [] = []
splitEvery n xs = as : splitEvery n bs 
  where (as,bs) = splitAt n xs

Context

StackExchange Code Review Q#48552, answer score: 13

Revisions (0)

No revisions yet.