fork download
  1. import Data.Maybe (isJust, listToMaybe)
  2. -- Find linear combinations of positive integers
  3. solve :: Integer -> [Integer] -> Maybe [Integer]
  4. -- If we've made it to the end with zero left, good!
  5. solve 0 [] = Just []
  6. -- Otherwise, this way isn't the way to go.
  7. solve _ [] = Nothing
  8. -- If one of the elements of the input list is zero, just multiply that element by one.
  9. solve n (0:xs) = case solve n xs of
  10. Nothing -> Nothing
  11. Just ys -> Just (1:ys)
  12. solve n (x:xs) = listToMaybe -- take first solution if it exists
  13. . map (\ (m, Just ys) -> m:ys) -- put multiplier at front of list
  14. . filter (isJust . snd) -- remove nonsolutions
  15. . zip [1 ..] -- tuple in the multiplier
  16. . map (\ m -> solve (n - m) xs) -- use each multiple
  17. $ [x, x + x .. n] -- the multiples of x up to n
  18.  
  19. main = mapM_ print [solve 11 [1, 2], solve 1 [1, 2]]
Success #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Just [1,5]
Nothing