[plt-scheme] A curious evaluation order (?) bug

From: Noel Welsh (noelwelsh at gmail.com)
Date: Sat Dec 29 11:26:31 EST 2007

Here's something curious.  I have code that samples from a discrete
distribution, and it does not behave as I would expect.  The code is
thus:

(define (sample-cluster-mixture state discrete)
  (define clusters (state-clusters state))
  (define i (random-discrete discrete))
  (printf "SAMPLE CLUSTER MIXTURE ~a\n" i)
  (printf "~a ~a\n" (discrete-pdf discrete 0)
          (discrete-pdf discrete 1))
  (random-seed 1234)
  ;(display (random-discrete discrete))
  (if (zero? i)
      (sample-new-cluster state)
      (vector-ref clusters i)))

The important thing here is the value of i, which is printed out.

I call (random-seed 1234) and run it, and the output is this:

SAMPLE CLUSTER MIXTURE 1
0.41176470588235303 0.588235294117647
0

So i is 1

I uncomment the display line and run it, and get:

SAMPLE CLUSTER MIXTURE 0
0.41176470588235303 0.588235294117647
0

So now i is 0

Note that i is evaluated before the call to display.  All I can think
it that this is an optimiser bug, reordering expressions in some
illegal way.  I'm using  v371.4 [3m].  I've just svn up'ed and I'll
try v4 and 372 to see if there is any difference.  If not I'll try to
narrow the bug down.

Consider this a preliminary report only.  I was so surprised by this
(having spent an few hours debugging) I had to let the world know...

N.


Posted on the users mailing list.