将列表分组到Haskell中n个元素的列表中 [英] Grouping a list into lists of n elements in Haskell
问题描述
在库中的列表中是否有对n个元素进行组合的操作?例如:n = 3
groupInto 3 [1,2,3,4,5,6,7,8,9 ] = [[1,2,3],[4,5,6],[7,8,9]]
如果不是,我该怎么做? 快速搜索 Hoogle 显示没有这样的功能。另一方面,有人回复说 split
包中有一个叫做 chunksOf
。
然而,你可以自己做到这一点
group :: Int - > ; [a] - > [[a]]
group _ [] = []
group n l
| n> 0 =(取n l):(组n(下降n l))
|否则=错误Negative n
当然,可以删除一些括号,了解代码的作用:
基本情况很简单:只要列表为空,只需返回空列表。
如果 n
是正数,则递归案例首先测试。如果 n
是 0
或更低,我们将进入一个无限循环,我们不希望这样做。然后我们使用将列表分成两部分以
和 drop
: take
返回第一个 n
元素,而 drop
返回其他元素。然后,我们将第一个 n
元素添加到通过将我们的函数应用到原始列表中的其他元素而获得的列表中。
Is there an operation on lists in library that makes groups of n elements? For example: n=3
groupInto 3 [1,2,3,4,5,6,7,8,9] = [[1,2,3],[4,5,6],[7,8,9]]
If not, how do I do it?
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.
这篇关于将列表分组到Haskell中n个元素的列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!