且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将列表分组到Haskell中n个元素的列表中

更新时间:2023-02-17 18:03:02

A quick search on Hoogle showed that there is no such function. On the other hand, it was replied that there is one in the split package, called chunksOf.

However, you can do it on your own

group :: Int -> [a] -> [[a]]
group _ [] = []
group n l
  | n > 0 = (take n l) : (group n (drop n l))
  | otherwise = error "Negative n"

Of course, some parentheses can be removed, I left there here for understanding what the code does:

The base case is simple: whenever the list is empty, simply return the empty list.

The recursive case tests first if n is positive. If n is 0 or lower we would enter an infinite loop and we don't want that. Then we split the list into two parts using take and drop: take gives back the first n elements while drop returns the other ones. Then, we add the first n elements to the list obtained by applying our function to the other elements in the original list.