We generalize the problem to finding n
integers that sum up to t
. As
everything in Haskell, this function will be recursive in nature and we will
need to provide it 4 arguments.
n
t
- A list of elements included in our sum
- The remaining elements
Thus we get something which looks like
try_sums :: Integer -> Integer -> [Integer] -> [Integer] -> Maybe Integer
try_sums t 0 as _ = if sum as == t then Just (product as) else Nothing -- Base 1
try_sums _ _ _ [] = Nothing -- Base 2
try_sums t n as (b:bs) = try_sums t (n - 1) (b:as) bs <|> try_sums t n as bs -- Recursive
which has the following cases:
- This base case is exactly as we imagine it. If there are no more elements to
include into the sum list, we check the sum against
t
and return the product if it is correct. - This is the next case we are interested in. Because the first case matches
n = 0
, this case matchesn != 0
and no more numbers, which should fail. - The main recursive case is pretty simple. Now that we know that there are
elements in the remaining list, we either include it or we don’t, and we ask
that
Alternative
picks the first success.