简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM