[plt-scheme] how do you use stream-partition?

From: Jos Koot (jos.koot at telefonica.net)
Date: Sun Mar 16 18:25:20 EDT 2008

The code of Phil bewig is more elegant and more general, I admit, but it 
uses internal state too, namely within procedure stream-unfolds, although 
without mutation. Procedure stream-unfolds produces streams with dummy 
elements that are skipped while the streams are traversed. The produced 
streams do see the presence of the other streams and must take care of that. 
The code of Phil calls the predicate twice for the very first element (now I 
am splitting hair :-)
Jos

----- Original Message ----- 
From: "Doug Orleans" <dougorleans at gmail.com>
To: "Jos Koot" <jos.koot at telefonica.net>
Cc: "PLT-Scheme Mailing List" <plt-scheme at list.cs.brown.edu>
Sent: Sunday, March 16, 2008 10:28 PM
Subject: Re: [plt-scheme] how do you use stream-partition?


> Jos Koot writes:
> > Therefore both streams must have state that can can be modified by
> > both.
>
> The author of SRFIs 40 and 41 sent me the following message (forwarded
> with permission).  Seems like there's no need for mutable state to
> implement stream-partition.  (By the way, are there plans to
> incorporate SRFI-41 into PLT?  Note that stream-partition is not
> actually provided by SRFI-41, it's just an example from the docs, so
> there's still a need for a utility package like stream.plt.)
>
> --dougorleans at gmail.com
>
>
> ------- start of forwarded message -------
> From: "Phil Bewig" <pbewig at gmail.com>
> To: "Doug Orleans" <dougorleans at gmail.com>
> Subject: Re: [plt-scheme] how do you use stream-partition?
> Date: Sat, 15 Mar 2008 12:26:44 -0500
>
> SRFI-40 is deprecated in favor of SRFI-41.  SRFI-41 gives stream-partition
> as an example, in the discussion of stream-unfolds, and shows how to use 
> the
> two streams that it returns.  Quoting SRFI-41:
>
> Stream-unfolds is especially useful when writing expressions that return
> multiple streams. For instance, (stream-partition *pred?* *strm*) is
> equivalent to
>
> (values
>  (stream-filter *pred?* *strm*)
>  (stream-filter
>    (lambda (x) (not (*pred?* x))) *strm*))
>
> but only tests * pred?* once for each element of *strm*.
>
> (define (stream-partition pred? strm)
>  (stream-unfolds
>    (lambda (s)
>      (if (stream-null? s)
>          (values s '() '())
>          (let ((a (stream-car s))
>                (d (stream-cdr s)))
>            (if (pred? a)
>                (values d (list a) #f)
>                (values d #f (list a))))))
>    strm))
>
> (call-with-values
>  (lambda ()
>    (stream-partition odd?
>      (stream-range 1 6)))
>  (lambda (odds evens)
>    (list (stream->list odds)
>          (stream->list evens))))
> => ((1 3 5) (2 4))
>
> ------- end of forwarded message ------- 



Posted on the users mailing list.