我正在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]]
如何修改给定代码才能获得此结果?
答案 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