AtlatestRepositorysigil-r7rs

sigil-r7rs / tree / src / schemelazy.sgl

1;;; (scheme lazy) - R7RS Lazy Evaluation Library
2;;;
3;;; Lazy evaluation with promises. Defer computation until explicitly needed
4;;; with `force`. Promises cache their result so repeated forcing is efficient.
5;;;
6;;; See: [R7RS Small](https://small.r7rs.org/) §4.2.5
7
8(define-library (scheme lazy)
9 (export delay
10 delay-force
11 force
12 make-promise
13 promise?)
15 (begin
16 ;; delay and delay-force are syntaxes provided by the prelude
18 ;;; Force evaluation of a promise.
19 ;;;
20 ;;; If the promise has not been forced before, evaluates its expression
21 ;;; and caches the result. Returns the cached value on subsequent calls.
22 ;;;
23 ;;; ```scheme
24 ;;; (define p (delay (begin (display "computing...") 42)))
25 ;;; (force p) ; prints "computing...", returns 42
26 ;;; (force p) ; returns 42 (no output, cached)
27 ;;; ```
28 (%set-docstring! force)
30 ;;; Create a promise from an already-computed value.
31 ;;;
32 ;;; Unlike `delay`, does not defer computation. The value is stored
33 ;;; immediately.
34 ;;;
35 ;;; ```scheme
36 ;;; (define p (make-promise 42))
37 ;;; (force p) ; => 42
38 ;;; (promise? p) ; => #t
39 ;;; ```
40 (%set-docstring! make-promise)
42 ;;; Test if an object is a promise.
43 ;;;
44 ;;; ```scheme
45 ;;; (promise? (delay 42)) ; => #t
46 ;;; (promise? (make-promise 1)) ; => #t
47 ;;; (promise? 42) ; => #f
48 ;;; ```
49 (%set-docstring! promise?)))