简体   繁体   中英

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? 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.

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 (tail prime-stream)) will then evaluate to (head nil) , which is a problem.

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

the tail might be '() and in that case, (head (tail)) would amount to (head'())

you need to replace your nil condition for this, cheking the tail of the tail instead and returning the final sum consed to '()

something like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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