user100106
user100106

Reputation: 141

Define function of list of integers such that their sum is n

I am trying to solve the following problem with Haskell:

Problem

Define the function sumToLists :: Int -> [[Int]] that, given a natural number n, it returns all the lists of positive numbers such that their sum is n.

I am pretty lost at this problem, maybe using recursion could yield up a solution but I have no clue how to attack this. Any suggestions would be greatly appreciated

Upvotes: 0

Views: 254

Answers (1)

talex
talex

Reputation: 20544

sumToLists 0 = [[]]
sumToLists n = [ i: xs | i <- [1..n], xs <- sumToLists (n - i) ] 

you need special case for 0 because default will return [] not [[]].

Upvotes: 2

Related Questions