Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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

  1. is there a better/more elegant way of performing same task?
  2. 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.

share|improve this question

1 Answer 1

up vote 4 down vote accepted

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
share|improve this answer
    
strangely enough, Hoogle is unable to find these functions. I've got a second question: when I search Hayoo for Int -> [a] -> [[a]] then chunksOf is not at top, but when I search Int -> [e] -> [[e]], then chunksOf is first. How am I supposed to guess what letter to use as a type variable? –  sukhmel Apr 30 '14 at 17:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.