Haskell函数返回列表的子列表

时间:2018-03-29 00:26:11

标签: list haskell

我正在Haskell中编写一个函数,当给出一个数字列表时,它将返回一个列表,其中包含该原始列表的所有子列表(按顺序)。到目前为止我所拥有的是:

sublists [] = [[]]
sublists (x:xs) = [x:sublist | sublist <- sublists xs] ++ sublists xs

上面的代码,如果给出[1,2,3],则返回[[1,2,3],[1,2],[1,3],[1],[2,3],[2],[3],[]],这不是我想要的。相反,该函数应该返回:

[[1],[1,2],[1,2,3]]

如何修改给定代码才能获得此结果?

1 个答案:

答案 0 :(得分:0)

为什么不将n列表中的第一个n元素置于1和输入长度之间?

sublists :: [a] -> [[a]]
sublists xs = [ take n xs | n <- [1..length xs] ]
> sublists [1,2,3]
[[1],[1,2],[1,2,3]]

或者使用递归和模式匹配

sublists' :: [a] -> [[a]]
sublists' xs = sublist [] xs where
    sublist a [b] = [ a ++ [b] ]
    sublist a (b:bs) = [ a ++ [b] ] ++ sublist (a ++ [b]) bs