在 Haskell 中将列表分组为 n 个元素的列表 [英] Grouping a list into lists of n elements in Haskell

查看:34
本文介绍了在 Haskell 中将列表分组为 n 个元素的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有对库中的列表进行操作以生成 n 个元素的组?例如:n=3

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?

推荐答案

快速搜索 Hoogle 显示没有这样的功能.另一方面,回复说split包中有一个,叫做chunksOf.

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.

不过,你可以自己做

group :: Int -> [a] -> [[a]]
group _ [] = []
group n l
  | n > 0 = (take n l) : (group n (drop n l))
  | otherwise = error "Negative or zero 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.

递归案例首先测试 n 是否为正.如果 n0 或更低,我们将进入无限循环,我们不希望那样.然后我们使用 将列表分成两部分takedrop:take 返回第一个 n 元素,而 drop 返回另一个那些.然后,我们将前 n 个元素添加到通过将我们的函数应用于原始列表中的其他元素而获得的列表中.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆