guile-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: stream-for-each 2 or more bug


From: Andy Wingo
Subject: Re: stream-for-each 2 or more bug
Date: Wed, 08 Sep 2004 20:37:07 +0200

Hi Kevin,

I'm sure I'm not the only one sitting slack-jawed when yet another one
of your well-written, well-documented patches shows up on the list. Just
wanted to let you know your work is appreciated, and that it's too bad
users have to wait until 1.8 to see them!

H

On Wed, 2004-09-08 at 11:37 +1000, Kevin Ryde wrote:
> I started some words about streams too.  stream-filter and stream-ref
> from sicp would be nice additions.

(define (stream-ref stream n)
  "Returns the @var{n}th element of @var{stream}."
  (if (negative? n) (error "Index must be nonnegative:" n))
  (let lp ((stream stream) (n n))
    (cond ((stream-null? stream) (error "Index out of range:" n))
          ((zero? n) (stream-car stream))
          (else (lp (stream-cdr stream) (1- n))))))

(define (stream-filter pass? stream)
  "Selects from @var{stream} only those elements that satisfy the
predicate @var{pass?}."
  (cond
   ((stream-null? stream) stream)
   ((pass? (stream-car stream))
    (stream-cons (stream-car stream)
                 (stream-filter pass? (stream-cdr stream))))
   (else
    (stream-filter pass? (stream-cdr stream)))))

(define (stream-remove deny? stream)
  "Removes from @var{stream} those elements that satisfy the predicate
@var{deny?}."
  (stream-filter (lambda (x) (not (deny? x))) stream))

Here's one that I've found to be useful, but I don't know how general it
is:

(define (stream-flatten stream)
  "Returns a stream that that will return all elements of @var{stream},
recursing into any contained streams. For example,
@example
  (stream->list
   (stream-flatten (list->stream (list 1 2
                                       (list->stream (list 3 4 5))
                                       6 7))))
  @result{} (1 2 3 4 5 6 7)
@end example"
  (cond
   ((stream-null? stream) stream)
   ((null? (stream-car stream))
    (stream-flatten (stream-cdr stream)))
   ((stream? (stream-car stream))
    (let lp ((recursed (stream-flatten (stream-car stream))))
      (if (stream-null? recursed)
          (stream-flatten (stream-cdr stream))
          (stream-cons (stream-car recursed)
                       (lp (stream-cdr recursed))))))
   (else
    (stream-cons (stream-car stream)
                 (stream-flatten (stream-cdr stream))))))

Regards,
-- 
Andy Wingo <address@hidden>
http://ambient.2y.net/wingo/




reply via email to

[Prev in Thread] Current Thread [Next in Thread]