无法使用我的递归函数来处理列表

时间:2011-09-28 20:31:33

标签: haskell

传入如下列表:[1,2,3,4,5] 并[[1,2,3,4,5],[2,3,4,5],[3,4,5],[4,5],[5],[]]

我的方法是使用递归将drop 1 list添加到另一个空列表,直到列表为空。但我似乎无法使我的递归正常工作。

请帮助,谢谢

到目前为止我的代码:

test a = test2 a where
test2 a | size(a) > 1 = test (drop 1 a):[]
        | otherwise = []

但这不起作用,因为递归会传回列表中的列表,而不是列表。我只是想弄清楚如何将它分配给某些东西并同时返回它。

4 个答案:

答案 0 :(得分:7)

首先,您为test a = test2 a做了什么?

然后,你不需要(也不应该使用)防护装置,用模式匹配来做:

test [] = [[]]
test (a:al) = (a:al):(test al)

如果您坚持使用警卫,您仍然需要将其列为实际列表:

test a
  | null a    = [[]]
  | otherwise = a:(test $ tail a)

(不是列表列表的列表,就像我在原帖中那样......)

答案 1 :(得分:6)

您所描述的功能已经在标准库中,它被称为Data.List.tails。您可以查看its source code以查看其工作原理。

答案 2 :(得分:1)

如果您想采用drop 1方法,可以写

test xs = take (1 + length xs) $ iterate (drop 1) xs

一个有趣的版本是

import Data.List

test = (++[[]]) . transpose . zipWith replicate [1..]

答案 3 :(得分:0)

fromNet [] = [[]]
fromNet lst =  lst : fromNet (tail lst)