gpt4 book ai didi

functional-programming - 具有所有中间值的列表的总和

转载 作者:行者123 更新时间:2023-12-01 11:22:23 26 4
gpt4 key购买 nike

我正在尝试计算一个包含所有中间值的列表的总和。我的代码如下,但它不起作用。

(: 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)))))

我正在家里自己学习 Racket ,所以任何帮助都将不胜感激!

最佳答案

所以你想写一个这样的函数

(sums (list))       = (list 0) ;; Your implementation has this right
(sums (list x)) = (list 0 x) = (list 0 (+ x 0))
(sums (list y x)) = (list 0 y (+ y x)) = (list 0 (+ y 0) (+ y (+ x 0)))
(sums (list z y x)) = (list 0 z (+ z y) (+ z y x)) = (list 0 (+ z 0) (+ z (+ y 0)) (+ z (+ y (+ x 0))))

等等(我在这里使用非常暗示性的名称、括号和布局,您会明白为什么)。

请注意,所有结果列表都以 0 开头,其余与上一行的结果相同,除了第一个输入项添加到每个后续项之外。

换句话说,我们有

(sums (car x items)) = (cons 0 (add-to-each x (sums items)))

所以首先你需要实现

(: add-to-each : Integer -> (Listof Integer))
(define (add-to-each x items)
...)

然后在 sums 的实现中使用它。要实现add-to-each,我们需要观察

(add-to-each x                   ())  =                               ()
(add-to-each x (cons y1 ())) = (cons (+ x y1) ())
(add-to-each x (cons y2 (cons y1 ())) = (cons (+ x y2) (cons (+ x y1) ()))

等等。

因为你说你这样做是为了学习 Racket,所以我会在这里停下来,看看你是否能从这里弄明白。

关于functional-programming - 具有所有中间值的列表的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40623506/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com