Search code examples
listfunctionhaskellfunctional-programmingpurely-functional

Haskell: Change a list of 100 numbers to 10 lists of 10 numbers?


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]]


Solution

  • 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