本文介绍了Haskell生成子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个函数'子集',它可以生成给定集合的所有子集:
子集:: [Int] - > [[Int]]
子集[] = [[]]
子集(x:xs)=子集xs ++映射(x :)(子集xs)
如何在另一个函数中结合map,foldl和filter来返回所有子元素总和为0的元素?
**例如:**
set = [1,-1,5 ,2,-2,3]
result = [[1,-1],[2,-2],[ - 1,-2,3]]
解决方案您已有子集。所以我们需要一个函数
filterSubs :: [[Int]] - > [[Int]]
filterSubs = - 删除所有不加和为0的子集
sumZero :: [Int] - > Bool
sumZero xs = sum xs == 0
现在,使用这个和
filter
很容易构造filterSubs
。我会把这个留给你来弄清楚它是如何工作的。然后我们的解决方案是微不足道的
zeroSubs = filterSubs。子集
I have a function 'subsets' which generate all the subsets of a given set:
subsets :: [Int] -> [[Int]] subsets [] = [[]] subsets (x:xs) = subsets xs ++ map (x:) (subsets xs)
How can I combine map, foldl and filter in another function to return me all the subsets with elements that sum up to 0?
**Example: **
set = [1,-1,5,2,-2,3] result = [[1,-1],[2,-2],[-1,-2,3]]
解决方案You have subsets already. So we need a function
filterSubs :: [[Int]] -> [[Int]] filterSubs = --remove all subsets which don't sum to 0
So next we'd need a predicate
sumZero :: [Int] -> Bool sumZero xs = sum xs == 0
Now, using this and
filter
it's easy to constructfilterSubs
. I'll leave this to you to figure out exactly how that works. And then our solution is trivialzeroSubs = filterSubs . subsets
这篇关于Haskell生成子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!