r7rs-lazy.scm 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. ;;; R7RS (scheme lazy) library
  2. ;;; Copyright (C) 2024 Igalia, S.L.
  3. ;;;
  4. ;;; Licensed under the Apache License, Version 2.0 (the "License");
  5. ;;; you may not use this file except in compliance with the License.
  6. ;;; You may obtain a copy of the License at
  7. ;;;
  8. ;;; http://www.apache.org/licenses/LICENSE-2.0
  9. ;;;
  10. ;;; Unless required by applicable law or agreed to in writing, software
  11. ;;; distributed under the License is distributed on an "AS IS" BASIS,
  12. ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. ;;; See the License for the specific language governing permissions and
  14. ;;; limitations under the License.
  15. ;;; Commentary:
  16. ;;;
  17. ;;; R7RS (scheme lazy) implementation
  18. ;;;
  19. ;;; Code:
  20. (library (scheme lazy)
  21. (export delay force promise? delay-force make-promise)
  22. (import (scheme base)
  23. (hoot match)
  24. (only (hoot primitives) define-syntax-rule))
  25. ;; promises
  26. (define-record-type <promise>
  27. #:opaque? #t
  28. (%%make-promise value)
  29. promise?
  30. (value %promise-value %set-promise-value!))
  31. (define (%make-promise eager? val)
  32. (%%make-promise (cons eager? val)))
  33. (define (make-promise x)
  34. (if (promise? x) x (%make-promise #t x)))
  35. (define (force promise)
  36. (match (%promise-value promise)
  37. ((#t . val) val)
  38. ((#f . thunk)
  39. (let ((promise* (thunk)))
  40. (match (%promise-value promise)
  41. ((and value (#f . _))
  42. (match (%promise-value promise*)
  43. ((eager? . data)
  44. (set-car! value eager?)
  45. (set-cdr! value data)
  46. (%set-promise-value! promise* value)
  47. (force promise))))
  48. ((#t . val) val))))))
  49. (define-syntax-rule (delay-force expr)
  50. (%make-promise #f (lambda () expr)))
  51. (define-syntax-rule (delay expr)
  52. (delay-force (%make-promise #t expr))))