Exercise3-5 <---> Exercise3-7

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.


Ru: Русский текст упражнения


Scheme solution:

(define rand
   (let ((random-number random-init))
      (lambda (action . new-value)
         (cond ((eq? action 'generate)
                  (set! random-number (rand-update random-number)) random-number)
               ((eq? action 'reset)
                  (set! random-number (car new-value)))
               (else (error "Unknown operation -- RAND"))))))

Other solutions goes here (use "#!code haskell", "#!code ocaml", etc. for syntax highlighting)

Exercise3-5 <---> Exercise3-7


Comments

I tested this by defining random-init and rand-update like so:

(define random-init (random 1000000)) (define (rand-update x) (random 1000000))

That's not exactly how they're supposed to behave, but they work well enough for testing.

Posted by GlenKaukola at 2009-09-10 04:40:23

:) :)) :( ;) :\ |) X-( B) Markup

Exercise3-6 (last edited 2009-09-10 01:37:21 by GlenKaukola)