[racket] What does "delay" delay?

From: Deren Dohoda (deren.dohoda at gmail.com)
Date: Fri Nov 18 13:45:46 EST 2011

Sorry about the other message, the enter key got in the way.

Consider this code:
----------------
#lang racket
(define x 10)
(define d (delay ((λ(x) (* x x)) x)))
(define d2 (* x x))
(define d3 (apply * (list x x)))
(define d4 (apply * `(,x ,x)))
(define d5 (apply (λ(x) (* x x)) (list x)))
(set! x 20)

(define (show)
  (for-each (λ(v) (displayln (force v))) (list d d2 d3 d4 d5)))
-----------------
I had expected a call to (show) to either display identical values, or
consider a few of them different. Instead, only the very first value
yields the substituted value for the variable x; all the others have
captured the value of 'x', including 'd5', which seems like it should
be identical to 'd' if any of them are.

Not that I make a habit of mixing mutation and delay---frankly I
forget now why I even fired up DrRacket to test this---but it was
quite surprising. The definition of delay says only: "Creates a
promise that, when forced, evaluates the bodys to produce its value."
I can't find an obvious reason why these five values aren't identical
under such a definition.

Deren



Posted on the users mailing list.