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


1.15.2 Definitions and constructors

Syntax: stream object ...

Take zero or more objects and create a newly–allocated ‘stream’ containing in its elements the objects, in order. Since stream is syntactic, the objects are evaluated when they are accessed, not when the ‘stream’ is created. If no objects are given, as in (stream), the null stream is returned. See also list->stream.

Example:

(define strm123 (stream 1 2 3))

; (/ 1 0) not evaluated when stream is created
(define s (stream 1 (/ 1 0) -1))
Function: stream-constant object ...

Take one or more objects and return a newly–allocated ‘stream’ containing in its elements the objects, repeating the objects in succession forever.

Example:

(stream-constant 1)
⇒ 1 1 1 ...

(stream-constant #t #f)
⇒ #t #f #t #f #t #f ...
Syntax: define-stream (name formals) . body

Create a procedure that returns a ‘stream’, and may appear anywhere a normal define may appear, including an internal definition, and may have internal definitions of its own, including other define-streams. The defined procedure takes arguments in the same way as stream-lambda.

define-stream is syntactic sugar on stream-lambda; see also stream-let.

The following example is a simple version of stream-map that takes only a single input stream and calls itself recursively:

(define-stream (stream-map proc strm)
  (if (stream-null? strm)
      stream-null
    (stream-cons
      (proc (stream-car strm))
      (stream-map proc (stream-cdr strm)))))
Syntax: stream-let name ((var expr) ...) body

Create a local scope that binds each variable to the value of its corresponding expression. Additionally bind name to a procedure which takes the bound variables as arguments and body as its defining expressions, binding the tag with stream-lambda. name is in scope within body, and may be called recursively.

When the expanded expression defined by stream-let is evaluated, stream-let evaluates the expressions in its body in an environment containing the newly–bound variables, returning the value of the last expression evaluated, which must yield a stream.

stream-let provides syntactic sugar on stream-lambda, in the same manner as normal let provides syntactic sugar on normal lambda. However, unlike normal let, the name is required, not optional, because unnamed stream-let is meaningless.

Example: stream-member returns the first ‘stream-pair’ of the input strm with a kar x that satisfies (eqv? obj x), or the null stream if x is not present in strm.

(define-stream (stream-member eql? obj strm)
  (stream-let loop ((strm strm))
    (cond ((stream-null? strm)
           strm)
          ((eqv? obj (stream-car strm))
           strm)
          (else
           (loop (stream-cdr strm))))))

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