Next: , Previous: , Up: srfi lazy   [Index]


2.24.4 Correct usage

We now provide a general recipe for using the primitives:

{lazy, delay, force}

to express lazy algorithms in Scheme. The transformation is best described by way of an example: Consider again the stream-filter algorithm, expressed in a hypothetical lazy language as:

(define (stream-filter p? s)
  (if (null? s) '()
      (let ((h (car s))
            (t (cdr s)))
        (if (p? h)
            (cons h (stream-filter p? t))
            (stream-filter p? t)))))

This algorithm can be espressed as follows in Scheme:

(define (stream-filter p? s)
  (lazy
     (if (null? (force s)) (delay '())
         (let ((h (car (force s)))
               (t (cdr (force s))))
           (if (p? h)
               (delay (cons h (stream-filter p? t)))
               (stream-filter p? t))))))

In other words, we:

  1. Wrap all constructors (e.g., (), cons) with delay.
  2. Apply force to arguments of deconstructors (e.g., car, cdr and null?).
  3. Wrap procedure bodies with (lazy …).

The only difference with the [Wad98] transformation described above is in replacing the combination (delay (force …)) with (lazy …) in the third rule.