lazy.scm 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 (except (scheme base) define-record-type)
  23. (hoot records)
  24. (hoot match)
  25. (only (hoot primitives) define-syntax-rule))
  26. ;; promises
  27. (define-record-type <promise>
  28. #:opaque? #t
  29. (%%make-promise value)
  30. promise?
  31. (value %promise-value %set-promise-value!))
  32. (define (%make-promise eager? val)
  33. (%%make-promise (cons eager? val)))
  34. (define (make-promise x)
  35. (if (promise? x) x (%make-promise #t x)))
  36. (define (force promise)
  37. (match (%promise-value promise)
  38. ((#t . val) val)
  39. ((#f . thunk)
  40. (let ((promise* (thunk)))
  41. (match (%promise-value promise)
  42. ((and value (#f . _))
  43. (match (%promise-value promise*)
  44. ((eager? . data)
  45. (set-car! value eager?)
  46. (set-cdr! value data)
  47. (%set-promise-value! promise* value)
  48. (force promise))))
  49. ((#t . val) val))))))
  50. (define-syntax-rule (delay-force expr)
  51. (%make-promise #f (lambda () expr)))
  52. (define-syntax-rule (delay expr)
  53. (delay-force (%make-promise #t expr))))