[plt-scheme] Could you give an example of the need of the second if in make-promise ?

From: Andre Mayers (andre.mayers at usherbrooke.ca)
Date: Wed Aug 23 12:49:31 EDT 2006

The following is an extract from TSPL3
(http://www.scheme.com/tspl3/control.html#./control:h6)
---
(define-syntax delay
  (syntax-rules ()
    ((_ exp) (make-promise (lambda () exp))))) 

where make-promise is defined as 

(define make-promise
  (lambda (p)
    (let ((val #f) (set? #f))
      (lambda ()
        (if (not set?)
            (let ((x (p)))
              (if (not set?)
                  (begin (set! val x)
                         (set! set? #t)))))
        val)))) 

With this definition of delay, force simply invokes the promise to force
evaluation or to retrieve the saved value. 

(define force
  (lambda (promise)
    (promise))) 

The second test of the variable set? in make-promise is necessary in the
unlikely event that, as a result of applying p, the promise is recursively
forced. Since a promise must always return the same value, the result of the
first application of p to complete is returned. 

 

----

André Mayers, Ph.D., M. Ps.
professeur agrégé
Département d'informatique
Université de Sherbrooke
Sherbrooke (Québec) Canada J1K 2R1
tél: +1 819-821-8000 poste 62041
fax: +1 819-821-8200
andre.mayers at usherbrooke.ca
http://www.dmi.usherb.ca/~amayers






Posted on the users mailing list.