DrRacket's call/cc

68 Views Asked by At
#lang racket

(let ((r (lambda (cont)
           (if (zero? (random 2))
               (+ 1000 6)
               (cont 6)))))
  (+ (* (+ (call/cc r) 3) 8)
     (* (+ (call/cc r) 3) 8)))

I have ran above code inside Racket IDE, and it give 3 different results 144, 16144, 8144. I can understand why the code outputs 144, and 16144, but I am confused why it outputs 8144

I am use DrRacket, version 8.11.1 under windows 10

1

There are 1 best solutions below

1
Shawn On BEST ANSWER

If (random 2) returns 0, r returns 1006, which then has 3 added to it (to get 1009) and is multiplied by 8, giving 8072. If it instead returns 1, r returns 6, which then has 3 added to it (to get 9) and is multiplied by 8, giving 72. Since r is called twice, each time returning either 3 or 1006, you get a number of possible results of summing the two values together:

first r second r result
6 6 144
6 1006 8144
1006 6 8144
1006 1006 16144

There's no point I can see to using call/cc here; it has no impact on the code, which can equivalently be written

(let ((r (lambda ()
           (if (zero? (random 2))
               (+ 1000 6)
               6))))
  (+ (* (+ (r) 3) 8)
     (* (+ (r) 3) 8)))