将列表分成Haskell中相同长度的子列表

时间:2013-03-07 22:01:27

标签: haskell

我正在尝试编写一个Haskell代码,该代码接收列表并返回列表列表。当我这样做时,我得到“函数reGroup中的非穷举模式”

reGroup :: [[Int]] -> [Int] -> [[Int]]
reGroup [[]] [] = [[]]
reGroup [[]] xs = reGroup [(take 3 xs)] (drop 3 xs)
reGroup [[a]] [] = [[a]]
reGroup [[a]] xs = reGroup [[a], (take 3 xs)] (drop 3 xs)

-- calling the reGroup function from another function as follow
reGroup [[]] [1,2,3,4,5,6,7,8,9]

我想要的是[1,2,3,4,5,6,7,8,9] - > [[1,2,3], [4,5,6], [7,8,9]]。我做错了什么或有人能告诉我一个简单的方法吗?

5 个答案:

答案 0 :(得分:7)

在没有累加器(第一个参数)的情况下尝试执行此操作可能更容易。那我们就有了

groupThree :: [a] -> [[a]] --why only work with Ints?
--if the list begins with three elements, stick them in a group
--then group the remainder of the list
groupThree (a:b:c:more) = [a,b,c]:groupThree more
--grouping an empty list gives you an empty list
groupThree [] = []
--if we have some number of elements less than three
--we can just stick them in a list
groupThree other = [other]

或使用drop并取

groupThree :: [a] -> [[a]]
groupThree [] = []
groupThree ls = (take 3 ls):groupThree (drop 3 ls)

完全相同。

您的代码不起作用的原因是

reGroup [xs,ls] y

与您的任何情况都不匹配 - 您只有代码来处理第一个参数是一个元素的列表,该元素是空列表或只有一个元素的列表。

正确使用累加器

reGroup back [] = back
reGroup back ls = reGroup (back ++ [take 3 ls]) (drop 3 ls)

不幸的是,这是非常低效的,因为你追加到列表的末尾(花时间与该列表的长度成正比...模数懒惰)。相反,你应该使用

reGroup back [] = reverse back
reGroup back ls = reGroup ((take 3 ls):back) (drop 3 ls)

虽然我喜欢没有累加器的版本更好,因为它更懒惰(因此可以处理无限列表)。

答案 1 :(得分:4)

 [[a]]

只是一个包含一个元素的列表的列表,如[[1]]。

所以在一次递归之后你会从

获得
reGroup [[]] [1,2,3,4,5,6,7,8,9]

reGroup [[1,2,3]] [4,5,6,7,8,9]

但是对于这种情况(包含3个元素的列表的列表)没有定义模式。

答案 2 :(得分:2)

试试这个:

reGroup xs n =
    if drop n xs == []
    then [take n xs]
    else [take n xs] ++ (reGroup (drop n xs) n)

可能不是最有效的,但它是一个开始。

输出:

> reGroup [1..9]
[[1,2,3],[4,5,6],[7,8,9]]
> reGroup [1..10]
[[1,2,3],[4,5,6],[7,8,9],[10]]

您获得该错误的原因是因为您尚未涵盖该功能可以匹配的所有模式。尝试为你的基本案例投入_或两个。

答案 3 :(得分:1)

稍微更改您的代码

reGroup :: [[Int]] -> [Int] -> [[Int]]; 
reGroup [[]] [] = []; 
reGroup a [] = a; 
reGroup [[]] xs = reGroup [(take 3 xs)] (drop 3 xs); 
reGroup a xs = a ++ reGroup [(take 3 xs)] (drop 3 xs); 

完成这项工作。

答案 4 :(得分:0)

take3 :: [a] -> [[a]]
take3 [] = []
take3 (x:[]) = [[x]]
take3 (x:y:[]) = [[x,y]]
take3 (x:y:z:xs) = [[x,y,z]] ++ take3 xs