chickadee » foof-loop » LAZY-LOOP

(LAZY-LOOP <loop-name> (<loop-clause> ...) => <final-expression> <body>)syntax

Lazily evaluated variant of LOOP which depends on SRFI 45 (Primitives for Expressing Iterative Lazy Algoritms). Equivalent to a LOOP form wrapped in LAZY with all calls to the <loop-name> also wrapped in LAZY. (See the SRFI 45 for details on LAZY.) The loop's body and final expression both must yield promises.

   ;;; Assume SRFI-40-style streams (see SRFI 40, A Library of
   ;;; Streams, for details, particularly on even versus odd streams).
   ;;; Also assume an IN-STREAM iterator.
   
   (define (stream-filter predicate stream)
     (lazy-loop filter ((for element (in-stream stream)))
       => stream-nil
       (if (predicate element)
           (stream-cons element (filter))
           (filter))))
   
   ;;; An equivalent definition of STREAM-FILTER.
   
   (define (stream-filter predicate stream)
     (lazy
      (loop filter ((for element (in-stream stream)))
        => stream-nil
        (if (predicate element)
            (stream-cons element (lazy (filter)))
            (lazy (filter))))))

The laziness annotations are added around the whole loop and around calls to the loop, rather than around the loop body, in order to delay any outer bindings of the loop (for example, many expressions supplied as arguments to loop iterators) and any loop variable updates when recursively invoking the loop.