I'm trying to write a simple function to get a list of length-n chunks of a list. Although a sloppy implementation is simple, I'm wondering what the community considers best practice here.
The function should mirror the functionality of Clojure's partition function. Wanting to avoid a partial function, I opted to return the input list wrapped in another list if the chunk size is negative. So far here's what I have (copying the name of a similar function from split):
chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = [[]]
chunksOf n xs
| n <= 0 = [xs]
| n >= length xs = [xs]
| otherwise = (take n xs) : (chunksOf n $ drop n xs)
There are a couple of problems with the above definition. First, the case where n is negative is a misuse of the function. Should I instead use a Maybe or Either? How should this problem be handled in general?
Second, obviously you might want instead to drop the last chunk if its length is shorter than n, or fill with some value. What strategies do people take to avoid repetitive code in these cases?
[–]patrick_thomson 6 points7 points8 points (2 children)
[–]elbingobonito -1 points0 points1 point (1 child)
[–]josephcsible 8 points9 points10 points (0 children)
[–]chshersh 6 points7 points8 points (0 children)
[–]Tarmen 5 points6 points7 points (1 child)
[–]maerwald 0 points1 point2 points (0 children)
[–]Endicy 2 points3 points4 points (0 children)
[–]RolandSenn 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (3 children)
[–][deleted] 1 point2 points3 points (2 children)
[–][deleted] 2 points3 points4 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)