| 1 |
#!r6rs |
| 2 |
;; Copyright André van Tonder. All Rights Reserved. |
| 3 |
;; |
| 4 |
;; Permission is hereby granted, free of charge, to any person |
| 5 |
;; obtaining a copy of this software and associated documentation |
| 6 |
;; files (the "Software"), to deal in the Software without |
| 7 |
;; restriction, including without limitation the rights to use, copy, |
| 8 |
;; modify, merge, publish, distribute, sublicense, and/or sell copies |
| 9 |
;; of the Software, and to permit persons to whom the Software is |
| 10 |
;; furnished to do so, subject to the following conditions: |
| 11 |
;; |
| 12 |
;; The above copyright notice and this permission notice shall be |
| 13 |
;; included in all copies or substantial portions of the Software. |
| 14 |
;; |
| 15 |
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
| 16 |
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
| 17 |
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND |
| 18 |
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS |
| 19 |
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN |
| 20 |
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN |
| 21 |
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 22 |
;; SOFTWARE. |
| 23 |
|
| 24 |
;; Modified by Andreas Rottmann to use records instead of mutable pairs. |
| 25 |
|
| 26 |
(library (srfi :45 lazy) |
| 27 |
(export delay |
| 28 |
lazy |
| 29 |
force |
| 30 |
eager) |
| 31 |
(import (rnrs base) |
| 32 |
(rnrs records syntactic)) |
| 33 |
|
| 34 |
(define-record-type promise |
| 35 |
(fields (mutable val))) |
| 36 |
|
| 37 |
(define-record-type value |
| 38 |
(fields (mutable tag) |
| 39 |
(mutable proc))) |
| 40 |
|
| 41 |
(define-syntax lazy |
| 42 |
(syntax-rules () |
| 43 |
((lazy exp) |
| 44 |
(make-promise (make-value 'lazy (lambda () exp)))))) |
| 45 |
|
| 46 |
(define (eager x) |
| 47 |
(make-promise (make-value 'eager x))) |
| 48 |
|
| 49 |
(define-syntax delay |
| 50 |
(syntax-rules () |
| 51 |
((delay exp) (lazy (eager exp))))) |
| 52 |
|
| 53 |
(define (force promise) |
| 54 |
(let ((content (promise-val promise))) |
| 55 |
(case (value-tag content) |
| 56 |
((eager) (value-proc content)) |
| 57 |
((lazy) (let* ((promise* ((value-proc content))) |
| 58 |
(content (promise-val promise))) ; * |
| 59 |
(if (not (eqv? (value-tag content) 'eager)) ; * |
| 60 |
(begin (value-tag-set! content |
| 61 |
(value-tag (promise-val promise*))) |
| 62 |
(value-proc-set! content |
| 63 |
(value-proc (promise-val promise*))) |
| 64 |
(promise-val-set! promise* content))) |
| 65 |
(force promise)))))) |
| 66 |
|
| 67 |
;; (*) These two lines re-fetch and check the original promise in case |
| 68 |
;; the first line of the let* caused it to be forced. For an example |
| 69 |
;; where this happens, see reentrancy test 3 below. |
| 70 |
|
| 71 |
) |