Download MIT Scheme Reference Manual
Transcript
Chapter 10: Miscellaneous Datatypes 121 (define count 0) (define p (delay (begin (set! count (+ count 1)) (* x 3)))) (define x 5) ⇒ 0 count ⇒ #[promise 54] p ⇒ 15 (force p) ⇒ #[promise 54] p ⇒ 1 count ⇒ 15 (force p) ⇒ 1 count Here is a possible implementation of delay and force. We define the expression (delay expression) to have the same meaning as the procedure call (make-promise (lambda () expression)) where make-promise is defined as follows: (define make-promise (lambda (proc) (let ((already-run? #f) (result #f)) (lambda () (cond ((not already-run?) (set! result (proc)) (set! already-run? #t))) result)))) Promises are implemented here as procedures of no arguments, and force simply calls its argument. (define force (lambda (promise) (promise))) Various extensions to this semantics of delay and force are supported in some implementations (none of these are currently supported in MIT Scheme): • Calling force on an object that is not a promise may simply return the object. • It may be the case that there is no means by which a promise can be operationally distinguished from its forced value. That is, expressions like the following may evaluate to either #t or #f, depending on the implementation: ⇒ unspecified (eqv? (delay 1) 1) ⇒ unspecified (pair? (delay (cons 1 2))) • Some implementations will implement “implicit forcing”, where the value of a promise is forced by primitive procedures like car and +: ⇒ 34 (+ (delay (* 3 7)) 13)