Lazy Evaluation, Promises and Streams
30.1 Promises
(define p (delay (begin (display "computing ") (* 6 7))))
(force p) ; prints "computing ", returns 42
(force p) ; 42 (memoized: not recomputed)
(promise? p) ; #t
(make-promise 5) ; an already-forced promise (R7RS)
(force (delay-force (delay 10))) ; 10: delay-force for iterative lazy algorithms (R7RS)30.2 Streams (SICP 3.5)
Libraries: SRFI-41 (streams with stream-cons, stream-lambda, define-stream), SRFI-158 (generators and accumulators), and SRFI-127 (lazy sequences).
(define-syntax cons-stream
(syntax-rules () ((_ a b) (cons a (delay b)))))
(define the-empty-stream '())
(define stream-null? null?)
(define (stream-car s) (car s))
(define (stream-cdr s) (force (cdr s)))
(define (stream-ref s n) (if (= n 0) (stream-car s) (stream-ref (stream-cdr s) (- n 1))))
(define (stream-map f s)
(if (stream-null? s) the-empty-stream
(cons-stream (f (stream-car s)) (stream-map f (stream-cdr s)))))
(define (stream-filter pred s)
(cond ((stream-null? s) the-empty-stream)
((pred (stream-car s)) (cons-stream (stream-car s) (stream-filter pred (stream-cdr s))))
(else (stream-filter pred (stream-cdr s)))))
(define (stream-take s n)
(if (or (= n 0) (stream-null? s)) '() (cons (stream-car s) (stream-take (stream-cdr s) (- n 1)))))
(define (add-streams s1 s2)
(cons-stream (+ (stream-car s1) (stream-car s2)) (add-streams (stream-cdr s1) (stream-cdr s2))))
;; Infinite streams
(define (integers-from n) (cons-stream n (integers-from (+ n 1))))
(define naturals (integers-from 0))
(stream-take (stream-filter even? naturals) 5) ; (0 2 4 6 8)
;; Implicitly defined streams
(define ones (cons-stream 1 ones))
(define integers (cons-stream 1
…(import (srfi 41))
(define-stream (stream-from n) (stream-cons n (stream-from (+ n 1))))
(stream->list (stream-take 5 (stream-from 10))) ; (10 11 12 13 14)