Haskell生成子集

时间:2013-11-04 16:35:57

标签: haskell subset-sum

我有一个函数'subsets',它生成给定集合的所有子集:

subsets :: [Int] -> [[Int]]
subsets []  = [[]]
subsets (x:xs) = subsets xs ++ map (x:) (subsets xs)

如何在另一个函数中组合map,foldl和filter以返回包含总和为0的元素的所有子集?

**示例:**

set    = [1,-1,5,2,-2,3]
result = [[1,-1],[2,-2],[-1,-2,3]]

2 个答案:

答案 0 :(得分:5)

你已经有了子集。所以我们需要一个函数

filterSubs :: [[Int]] -> [[Int]]
filterSubs = --remove all subsets which don't sum to 0

接下来我们需要一个谓词

sumZero :: [Int] -> Bool
sumZero xs = sum xs == 0

现在,使用此filter可以轻松构建filterSubs。我将把这个留给你,弄清楚它是如何工作的。然后我们的解决方案是微不足道的

zeroSubs = filterSubs . subsets

答案 1 :(得分:0)

这个想法是你想要获取所有子集,然后只保持那些sum 0

subsetsSum0 ls = filter (\ss -> (sum ss) == 0) (subsets ls)

让我们让这段代码免费

subsetsSum0 = filter ((==0) . sum) . subsets