7

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

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]]
4

2 回答 2

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
于 2013-11-04T16:53:26.383 回答
0

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

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

让我们让这个代码无点

subsetsSum0 = filter ((==0) . sum) . subsets
于 2013-11-04T16:55:54.833 回答