Haskell generate subsets

后端 未结 2 1239
南方客
南方客 2021-01-13 00:22

I have a function \'subsets\' which generate all the subsets of a given set:

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


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-13 00:36

    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
    

提交回复
热议问题