简体   繁体   English

方案中的递归求和函数

[英]Recursive sum function in scheme

I want to add all consecutive values in my stream and return a list. 我想在流中添加所有连续值并返回一个列表。 Like, stream : (1,2,3,4) output: (3,5,7) I have this code here but its giving me an error car: contract violation expected: pair? 像,流:(1,2,3,4)输出:(3,5,7)我在这里有这段代码,但是它给我一个错误的提示:违反合同预期:对吗? given: '() 给定:'()

I have tried using the head and tail separately and they are working fine! 我试过分别使用头和尾,它们工作正常! So whats wrong here ? 那这里怎么了?

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

You do check for the empty stream, and that prevents (head prime-stream) from failing. 您确实要检查是否有空数据流,这可以防止(head prime-stream)失败。

In the case of a stream with one element, (head prime-stream) will evaluate to the single element in the stream, and (tail prime-stream) will evaluate to nil . 在具有一个元素的流的情况下, (head prime-stream)将评估为(head prime-stream)中的单个元素,而(tail prime-stream)将评估为nil

(head (tail prime-stream)) will then evaluate to (head nil) , which is a problem. (head (tail prime-stream))然后将评估为(head nil) ,这是一个问题。

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

the tail might be '() and in that case, (head (tail)) would amount to (head'()) 尾巴可能是'(),在这种情况下,(头(尾))等于(head'())

you need to replace your nil condition for this, cheking the tail of the tail instead and returning the final sum consed to '() 您需要为此替换nil条件,取而代之的是咀嚼尾巴的尾巴,然后将最终的总和归纳为'()

something like 就像是

(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