繁体   English   中英

方案中的递归求和函数

[英]Recursive sum function in scheme

我想在流中添加所有连续值并返回一个列表。 像,流:(1,2,3,4)输出:(3,5,7)我在这里有这段代码,但是它给我一个错误的提示:违反合同预期:对吗? 给定:'()

我试过分别使用头和尾,它们工作正常! 那这里怎么了?

(define (sum-primes prime-stream)
  (if (empty-stream? prime-stream)
  '()
  (cons (+ (head prime-stream) (head (tail prime-stream)))
        (sum-primes (tail prime-stream)))))

您确实要检查是否有空数据流,这可以防止(head prime-stream)失败。

在具有一个元素的流的情况下, (head prime-stream)将评估为(head prime-stream)中的单个元素,而(tail prime-stream)将评估为nil

(head (tail prime-stream))然后将评估为(head nil) ,这是一个问题。

 (+ (head prime-stream) 
 (head (tail prime-stream))

尾巴可能是'(),在这种情况下,(头(尾))等于(head'())

您需要为此替换nil条件,取而代之的是咀嚼尾巴的尾巴,然后将最终的总和归纳为'()

就像是

(if (empty-stream? (cdr (cdr p)))
(+(car p) (car (cdr p)))
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM