CS 541 Lecture -*- Outline -*- * Iteration constructs discuss design alternatives structure principle, orthogonality, simplicity ** indefinite iteration while loop, until loop, loop + exit ** definite iteration *** for loop in Pascal, map and for-each in Scheme *** generalized iteration over abstract types (e.g., sets) alternatives: 1. add indexing operations (fetch) 2. add operation that returns array of elements (inefficient searching) 3. add operation to return the representation 4. add operation that takes a closure as arg, call for each element (how to escape?) *** streams (or generators) initialize (return loop-state object) done? (sees if loop-state is terminated) next (gets next element from loop-state) **** Streams in Scheme: the-empty-stream cons-stream head, tail empty-stream? **** efficiency from lazy evaluation (vs. enumeration) (cons-stream E1 E2) = (cons E1 (delay E2)) must be a special form, since Scheme is call by value otherwise (head stream) = (car stream) (tail stream) = (force (cdr stream)) e.g. iteration on sets implemented using vectors (define (set-iter set) (define (interal-iter set index) (cond ((> index (size set)) the-empty-stream) (else (cons-stream (vector-ref set index) (internal-iter set (+ 1 index)))))) (internal-iter set 0))