【发布时间】:2017-03-30 03:24:48
【问题描述】:
我正在尝试计算一个包含所有中间值的列表的总和。我的代码如下,但它不起作用。
(: 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 ...)。 -
你在最后一行有错误的括号。最后一个表达式是
(sums (cons a b)),append表达式无效。 (顺便说一句,(append (list a) (list b) (list c))与(list a b c)相同。) -
但是,您的方法可能行不通,因为您总是从 0 开始,但递归调用应该从更新的中间总和值开始。顺便说一句,这种计算称为 partial-sums(在 Haskell 中被抽象为高阶函数
scanl)。
标签: functional-programming scheme racket typed-racket