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


1.15.3 Converting objects into streams

Function: list->stream list-of-objects

Return a newly–allocated ‘stream’ containing in its elements the objects in the list. Since the objects are given in a list, they are evaluated when list->stream is called, before the ‘stream’ is created. If the list of objects is null, as in (list->stream '()), the null ‘stream’ is returned. See also stream.

Example:

(define strm123
  (list->stream '(1 2 3)))

;; fails with divide-by-zero error
(define s
  (list->stream (list 1 (/ 1 0) -1)))
Function: port->stream
Function: port->stream port

Return a newly–allocated ‘stream’ containing in its elements the characters on the port. If port is not given it defaults to the current input port. The returned ‘stream’ has finite length and is terminated by ‘stream-null’.

It looks like one use of port->stream would be this:

(define s               ;wrong!
  (with-input-from-file filename
    (lambda ()
      (port->stream))))

but that fails, because with-input-from-file is eager, and closes the input port prematurely, before the first character is read. To read a file into a stream, use:

(define-stream (file->stream filename)
  (let ((p (open-input-file filename)))
    (stream-let loop ((c (read-char p)))
      (if (eof-object? c)
          (begin (close-input-port p)
                 stream-null)
          (stream-cons c
            (loop (read-char p)))))))