6

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]]
recursion.ninja
  • 5,377
  • 7
  • 46
  • 78
orion
  • 101
  • 1
  • 4

2 Answers2

5

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 construct filterSubs. I'll leave this to you to figure out exactly how that works. And then our solution is trivial

zeroSubs = filterSubs . subsets
daniel gratzer
  • 52,833
  • 11
  • 94
  • 134
0

The idea is that you want to take all subsets and then only keep the ones that sum 0

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

let's make this code point-free

subsetsSum0 = filter ((==0) . sum) . subsets
chamini2
  • 2,820
  • 2
  • 24
  • 37