In today’s Programming Praxis problem, our goal is to find all the subsets of a list that sum up to a given number. Let’s get started, shall we?
Like the provided Scheme solution we choose the simple approach of determining all the subsets and summing them up. The main difference is that instead of making a hash table to remove duplicate additions I just use a simple fold.
subsetSum :: Num a => a -> [a] -> [[a]] subsetSum n xs = [ns | (total, ns) <- subsets xs, total == n] where subsets = foldr (\x a -> (x, [x]) : map (\(t, ns) -> (t+x, x:ns)) a ++ a) 
A quick test to see if everything is working properly:
main :: IO () main = print $ subsetSum 5842 [267, 439, 869, 961, 1000, 1153, 1246, 1598, 1766, 1922] == [[869,961,1000,1246,1766]]