[英]Define function of list of integers such that their sum is n
I am trying to solve the following problem with Haskell: 我正在尝试使用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
. 定义函数
sumToLists :: Int -> [[Int]]
,给定自然数n
,该n
返回所有正数列表,使它们的和为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 [[]]
. 您需要将
0
用作特殊情况,因为默认值将返回[]
而不是[[]]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.