How is sicp cons-stream implemented?

I am working on a thread section in scip and is fixated on how to define a thread.

Below is my code:

(define (memo-func function)
  (let ((already-run? false)
        (result false))
    (lambda ()
      (if (not already-run?)
          (begin (set! result (function))
                 (set! already-run? true)
                 result)
          result))))


(define (delay exp)
  (memo-func (lambda () exp)))

(define (force function)
  (function))

(define the-empty-stream '())
(define (stream-null? stream) (null? stream))
(define (stream-car stream) (car stream))
(define (stream-cdr stream) (force (cdr stream)))

(define (cons-stream a b) (cons a (memo-func (lambda () b))))

If I define integers as described in the book:

(define (integers-starting-from n)
   (cons-stream n (integers-starting-from (+ n 1))))
(define integers (integers-starting-from 1))

I get the message: Aborting !: recursion depth exceeded.

I assume that the delay function does not work, but I do not know how to fix it. I am running a MIT circuit on my Mac.

update 1

So now with cons-stream you can define integers as a macro.

But then I have another mistake.

(define (stream-take n s)
  (cond ((or (stream-null? s)
             (= n 0)) the-empty-stream)
        (else (cons-stream (stream-car s)
                           (stream-take (- n 1) (stream-cdr s))))))

(stream-take 10 integers)
;ERROR - Variable reference to a syntactic keyword: cons-stream

update 2

Please ignore update 1 above.

+5
source share
2 answers

cons-streammust be a macro for your sample code to work correctly. Otherwise, the challenge cons-streamwill evaluate all his arguments with impatience.

( ):

(define-syntax cons-stream
  (syntax-rules ()
    ((cons-stream a b)
     (cons a (memo-func (lambda () b))))))

P.S. delay . , delay, cons-stream delay.

+5

, Scheme - , . SICP , .

+1

All Articles