my attempt to do the exercises in sicp.

Thursday, January 6, 2011

sicp exercise 3.81

;; Exercise 3.81.  Exercise 3.6 discussed generalizing the random-number generator to allow one to reset the random-number sequence so as to produce repeatable sequences of ``random'' numbers. Produce a stream formulation of this same generator that operates on an input stream of requests to generate a new random number or to reset the sequence to a specified value and that produces the desired stream of random numbers. Don't use assignment in your solution.

(define (display-line str)
  (display str)

(define (display-stream str num)
  (define (internal index)
    (if (> index num) 'printed
          (display-line (stream-ref str index))
          (internal (+ 1 index)))))
  (internal 0))

(define (random-numbers input-stream rand-init)
  (define (rand-update n)(+ 10 n))
    (let ((command (stream-car input-stream)))
      (cond ((eq? command 'generate)
             (let ((random-number (rand-update rand-init)))
               (cons-stream random-number
                            (random-numbers (stream-cdr input-stream) random-number))))
            ((and (pair? command) (eq? (car command) 'reset))
              (let ((random-number (rand-update (cadr command))))
                (cons-stream random-number
                             (random-numbers (stream-cdr input-stream) random-number))))

(define infinite-input
  (cons-stream 'generate infinite-input))

(display-stream (random-numbers infinite-input 0) 20)

(define input
  (cons-stream 'generate
    (cons-stream 'generate
      (cons-stream 'generate
        (cons-stream (list 'reset 2)
          (cons-stream 'generate
            (cons-stream 'generate
              (cons-stream 'generate '()))))))))

(display (stream-ref (random-numbers input 0) 0))(newline)
(display (stream-ref (random-numbers input 0) 1))(newline)
(display (stream-ref (random-numbers input 0) 2))(newline)
(display (stream-ref (random-numbers input 0) 3))(newline)
(display (stream-ref (random-numbers input 0) 4))(newline)
(display (stream-ref (random-numbers input 0) 5))(newline)
(display (stream-ref (random-numbers input 0) 6))(newline)

;Loading "sicp_prob_03.81.scm"...
;... done

No comments: