组合递归函数的意外结果

时间:2019-12-23 22:11:43

标签: haskell recursion

在从1开始的上限(n)之前,我有一个以特定幂(x)形成的自然数序列,例如,幂是n = 2和{{1 }}的顺序是x = 5。基于该数字,只要集合中1个或多个值的总和返回[1, 4, 9, 16, 25],我就必须找到所有可能的组合。一些例子:

  • x代表[[1,4]]x = 5
  • n = 2代表[[1,9]]x = 10
  • n = 2代表[[1, 8, 27, 64]]x = 100
  • 依此类推

我编写了以下代码:

n = 3

但是返回的结果是:

combinations :: Int -> [Int] -> [[Int]] -> [[Int]]
combinations t l@(x:xs) a
    | sum l == t  = a ++ [l]
    | otherwise   = (map (x:) (combinations t xs a)) ++ (combinations t xs a)
combinations _ [] a = a

calcPowers x n = filter (<=x) (map (^n) [1..x])

combos x n = combinations x (calcPowers x n) []::[[Int]]

知道为什么它不返回正确的序列吗?

1 个答案:

答案 0 :(得分:0)

(map (x:) (combinations t xs a))是不正确的,因为您将在x之前加上前缀,所以该组合应与其余部分匹配:

(map (x:) (combinations (t-x) xs a))

在某些时候t将变为零,并且一个空列表应为该零产生结果。

combinations 0 [] a = []:a
combinations _ [] a = a