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

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

最佳答案

您已经有子集。所以我们需要一个功能

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

关于haskell - Haskell生成子集,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19772427/

10-11 17:50