1

In Haskell, how does one change a list of x numbers into n lists of n numbers?

The first sublist would have numbers first to tenth, second list 11th to 20th...

myFunction :: [Int] -> [[Int]]

Mickael Bergeron Néron
  • 1,472
  • 1
  • 18
  • 31

2 Answers2

5

There is the chunksOf function in Data.List.Split:

chunksOf 2 [0, 1, 2, 3] -- [[0, 1], [2, 3]]

Alternatively, we already have splitAt in prelude, with which chunksOf can be implemented with ease:

chunksOf :: Int -> [a] -> [[a]]
chunksOf n [] = []
chunksOf n xs = let (as, bs) = splitAt n xs in as : chunksOf n bs
András Kovács
  • 29,931
  • 3
  • 53
  • 99
  • note that in older versions of ghc you have to 'cabal install split' (i think before 7.6) – epsilonhalbe Jun 16 '14 at 20:52
  • Why oh why isn't an equivalent in Prelude? I don't want o depend on the split package if I'm writing something quick & small. – Alex Feb 14 '16 at 16:58
3

Might be a little simpler to read with take and drop and requires no libraries.

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf n xs = take n xs : chunksOf n (drop n xs)
mmachenry
  • 1,773
  • 3
  • 22
  • 38