[racket] idiomatic way to take elements from a thunk?

From: Asumu Takikawa (asumu at ccs.neu.edu)
Date: Thu Sep 20 00:39:24 EDT 2012

On 2012-09-19 20:57:59 -0700, John Clements wrote:
> (define thunk (lambda () 14))
> (for/list ([i 10][e (in-producer thunk #f)]) e)
> … but I feel like there must be some way to simply write (stream-take
> thunk 10). Am I missing something obvious?

How about

  (for/list ([i 10]) (thunk))

? Or do you really want it to be a stream?

You could write `stream-take` and use `in-producer`, but unfortunately
sequences are not necessarily streams, so it doesn't seem to be much

  (require unstable/match)

  (define/match (stream-take strm n)
    [((? stream-empty?) n) empty-stream]
    [(_ 0) empty-stream]
    [(strm n) (stream-cons (stream-first strm)
                           (stream-take (stream-rest strm)
                                        (sub1 n)))])

  (stream-take (sequence->stream (in-producer thunk #f)) 10)

BTW: should `racket/stream` have `stream-take` and other friends like
`stream-drop`? They're in SRFI-41.


Posted on the users mailing list.