哈斯克尔列表错误的部分总和

问题描述:

例如

我需要在Haskell中编写一个函数来对列表中的元素进行求和,直到某些特定元素存储在另一个列表中。 partial_add [1,2,3,4,5,6] [2,5] 0 应返回 [3,12,6]

For example partial_add [1,2,3,4,5,6] [2,5] 0 should return [3,12,6].

我已经到达这个地步了:

I have reached this far:

partial_add [] _ count = []
partial_add (a:x) list count | elem a list =  count:partial_add x list 0
                             | otherwise =  partial_add x list count+a

(很可能工作不正常)

但是当我尝试运行该函数时(它编译正确),我得到这个错误:

But when I try to run the function (it compiles properly) I get this error:

No instance for (Num [t0]) arising from a use of `it' 
In a stmt of an interactive GHCi command: print it

有什么想法发生了什么?

Any idea what's going on?

这个函数就像这样:

Given your example, I would write the function something like this:

partialAdd :: [Int] -> [Int] -> [Int]
partialAdd ls seps = foldr f [] ls
  where 
    f a [] = [a]
    f a (x:xs)
      | a `elem` seps = a:x:xs
      | otherwise = (x+a):xs

*Main> partialAdd [1,2,3,4,5,6] [2,5]
[3,12,6]

顺便说一句。我认为你的问题的解决方案似乎不像你在你的例子中指定的方式工作(或者我误解了某些东西):

Btw. I think the solution in your question seems not to work quite the way you specified in your example (or I misunderstood something):

partial_add :: [Int] -> [Int] -> Int -> [Int]
partial_add [] _ count = []
partial_add (a:x) list count | elem a list =  count:partial_add x list 0
                             | otherwise =  partial_add x list (count+a)

*Main> partial_add [1,2,3,4,5,6] [2,5] 0
[1,7]

但是它可以很容易地解决您的问题:

But it is easily fixed to work for your example:

partial_add :: [Int] -> [Int] -> Int -> [Int]
partial_add [] _ count = [count]
partial_add (a:x) list count | elem a list =  (count+a):partial_add x list 0
                             | otherwise =  partial_add x list (count+a)

*Main> partial_add [1,2,3,4,5,6] [2,5] 0
[3,12,6]