Next: , Previous: , Up: streams   [Index]


1.15.6 Selecting

Function: stream-drop n stream

Return the suffix of the input stream that starts at the next element after the first n elements. The output stream shares structure with the input stream; thus, promises forced in one instance of the stream are also forced in the other instance of the stream. If the input stream has less than n elements, stream-drop returns the null stream. See also stream-take.

Example:

(define (stream-split n strm)
  (values (stream-take n strm)
          (stream-drop n strm)))
Function: stream-drop-while pred stream

Return the suffix of the input stream that starts at the first element x for which (pred x) is #f. The output stream shares structure with the input stream. See also stream-take-while.

Example: stream-unique creates a new stream that retains only the first of any sub–sequences of repeated elements.

(define-stream (stream-unique item= strm)
  (if (stream-null? strm)
      stream-null
    (stream-cons (stream-car strm)
      (stream-unique item=
        (stream-drop-while
          (lambda (x)
            (item= (stream-car strm) x))
          strm)))))
Function: stream-take n stream

Take a non–negative exact integer n and a stream and return a newly–allocated stream containing the first n elements of the input stream. If the input stream has less than n elements, so does the output stream. See also stream-drop.

Example: merge-sort splits a stream into two equal–length pieces, sorts them recursively and merges the results:

(define-stream (merge-sort lt? strm)
  (let* ((n     (div (stream-length strm) 2))
         (ts    (stream-take n strm))
         (ds    (stream-drop n strm)))
    (if (zero? n)
        strm
      (stream-merge lt? (merge-sort < ts) (merge-sort < ds)))))
Function: stream-take-while pred stream

Take a predicate and a stream and return a newly–allocated stream containing those elements x that form the maximal prefix of the input stream for which (pred x) is non–#f. See also stream-drop-while.

(stream-car
  (stream-reverse
    (stream-take-while
      (lambda (x) (< x 1000))
      primes)))
⇒ 997
Function: stream-filter pred stream

Return a newly–allocated stream that contains only those elements x of the input stream for which (pred x) is true.

Example:

(stream-filter odd? (stream-from 0))
⇒ 1 3 5 7 9 ...

Next: , Previous: , Up: streams   [Index]