6.8 mischief/stream: Streams
(require mischief/stream) | package: mischief |
syntax
(define-stream id expr)
Defines id as a lazy stream encapsulating expr.
Examples:
> (define-stream naturals (stream-cons 0 (stream-map add1 naturals))) > naturals #<delayed>
> (stream-ref naturals 0) 0
> (stream-ref naturals 1) 1
> (stream-ref naturals 2) 2
syntax
(stream-delay expr)
Constructs a lazy stream encapsulating expr.
Examples:
> (define delayed-stream (stream-delay '(1 2 3))) > delayed-stream #<delayed>
> (stream? delayed-stream) #t
> (stream-empty? delayed-stream) #f
> (stream-first delayed-stream) 1
> (stream? (stream-delay 'not-a-stream)) #t
> (stream-empty? (stream-delay 'not-a-stream)) stream-delay: contract violation
expected: stream?
given: 'not-a-stream
Creates a lazy stream that contains each x followed by the contents of
st.
Examples:
> (define (nonzero-integers-from k) (stream* k (- k) (nonzero-integers-from (add1 k))))
> (define nonzero-integers (nonzero-integers-from 1)) > (stream-ref nonzero-integers 0) 1
> (stream-ref nonzero-integers 1) -1
> (stream-ref nonzero-integers 2) 2
> (stream-ref nonzero-integers 3) -2
> (stream-ref nonzero-integers 4) 3
procedure
(stream-take st n) → list?
st : stream? n : exact-nonnegative-integer?
Produces a list containing the first n elements of st.
Example:
> (stream-take (stream 1 2 3 (error "Oops!")) 3) #<stream>
procedure
(stream-zip st ...+) → stream?
st : stream?
Creates a lazy stream containing lists of the respective elements of each
st.
Example:
> (stream->list (stream-zip (stream 1 2 3) (stream 'a 'b 'c))) '((1 a) (2 b) (3 c))
procedure
(stream-interleave st ...) → stream?
st : stream?
Creates a lazy stream that alternates the elements of the given sts.
Example:
> (stream->list (stream-interleave (stream 1 2 3) (stream 'a 'b 'c))) '(1 a 2 b 3 c)
procedure
(stream-interleave* st) → stream?
st : stream?
Creates a lazy stream from st, which must be a stream of streams. The
resulting stream includes all of the elements from the streams in st,
even if st is an infinite stream of streams.
Example:
> (stream->list (stream-interleave* (stream (stream 1 2 3) (stream 'a 'b 'c)))) '(1 2 a 3 b c)
procedure
(stream-cross-product f st1 st2) → stream?
f : (-> any/c any/c any/c) st1 : stream? st2 : stream?
Creates a lazy stream whose elements are the results of applying f to
every pairwise combination of elements from st1 and st2.
Example:
> (stream->list (stream-cross-product string-ref (stream "cat" "dog") (stream 2 1 0))) '(#\t #\g #\a #\o #\c #\d)
procedure
(stream-cross-product* f st1 st2) → stream?
f : (-> any/c any/c any/c) st1 : stream? st2 : stream?
Creates a lazy stream of streams whose elements are the results of applying
f to every pairwise combination of elements from st1 and
st2.
Example:
> (map stream->list (stream->list (stream-cross-product* string-ref (stream "cat" "dog") (stream 2 1 0)))) '((#\t #\g) (#\a #\o) (#\c #\d))