我正试图计算列表中所有中间值的总和。我的代码如下,但它不起作用。带有所有中间值的列表的总和
(: sums : (Listof Integer) -> (Listof Integer))
;; compute the sum of a list,
;; produce all the intermediate sums along the way
;; start with 0
;; (sums (list 1 2 3 4)) ==> (list 0 1 3 6 10)
(define (sums x)
(match x
('() (list 0))
((cons hd '()) (append (list 0) (list (+ 0 hd))))
((cons hd (cons a b))
(append (list 0) (list (+ 0 hd)) (list (+ 0 hd a))) (sums (cons a b)))))
我从我自己的家里学习球拍,所以任何和所有的帮助将不胜感激!
而不是'(append(list 0)..)',使用'(cons 0 ...)'。 – Cactus
你在最后一行中有错误的括号。最后一个表达式是'(summs(cons a b))','append'表达式不起作用。 (和btw'(追加(列表a)(列表b)(列表c))'与(列表abc)'相同。) –
但是,你的方法不可能工作,因为你总是从0开始,但递归调用应该从更新的中间和值开始。这种计算称为*部分和*(并且在例如Haskell中被抽象为高阶函数'scanl')。 –