Exercise 3.6.  It is useful to be able to reset a random-number generator to produce a sequence starting from a given value. Design a new rand procedure that is called with an argument that is either the symbol generate or the symbol reset and behaves as follows: (rand 'generate) produces a new random number; ((rand 'reset) <new-value>) resets the internal state variable to the designated <new-value>. Thus, by resetting the state, one can generate repeatable sequences. These are very handy to have when testing and debugging programs that use random numbers.

 


(define random-init 7) ;**not in book**
(define rand
(let
((x random-init))
(define (dispatch m)
(cond
((eq? m 'generate)
(begin
(set! x (random x))
x))
((eq? m 'reset)
(lambda (new-value)
(set! x new-value)))))
dispatch))
(rand 'generate)
; 1
(rand 'generate)
; 2
((rand 'reset) 0)
; 0
(rand 'generate)
; 1

view raw

s306.scm

hosted with ❤ by GitHub

 

Discover more from Gaurav Sharma's Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading