20 hours ago
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)
(newline))
(define (display-stream str num)
(define (internal index)
(if (> index num) 'printed
(begin
(display-line (stream-ref str index))
(internal (+ 1 index)))))
(newline)
(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))))
(else
'()))))
(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 '()))))))))
(newline)
(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"...
;10
;20
;30
;40
;50
;60
;70
;80
;90
;100
;110
;120
;130
;140
;150
;160
;170
;180
;190
;200
;210
;
;10
;20
;30
;12
;22
;32
;42
;... done
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment