streams in racket

后端 未结 4 1313
情话喂你
情话喂你 2021-01-05 06:44

Can anyone help me better understand how to write a stream?

I understand that a stream is an infinite sequence of values and the way I have learned programming them

相关标签:
4条回答
  • 2021-01-05 07:13

    It looks like you were asking how to build your own custom streams with thunks, which others have already answered. Just in case, it's worth noting that Racket has a stream library built-in and most Racketeers would use that for streams.

    Here's an example:

    #lang racket
    (require racket/stream)
    (define reds (stream-cons "red" reds))
    (define red-blues (stream-add-between reds "blue"))
    
    ;; show ten of them
    (for ([i 10] [e (in-stream red-blues)])
      (displayln e))
    
    0 讨论(0)
  • 2021-01-05 07:16

    I am a newbie at this but the following solutions seems to work as well:

     (define red-then-blue
       (letrec ([f (lambda (x) (cons x(lambda ()(f(cond [(string=? x "red") "blue"]
                                                  ["red"])))))])
       (lambda () (f "red"))))
    
    0 讨论(0)
  • 2021-01-05 07:20

    For a general understanding of streams in Scheme, I'd recommend section §3.5 Streams in the SICP book. It'll teach you the basic concepts to solve stream-related problems such as the one in the question.

    Regarding the problem in the question, here's the general idea to solve it:

    • Build two infinite streams, one producing only the string "red" and the other "blue"
    • Combine both streams taking one element from one and then one element from the other (alternating), this procedure is called interleave in SICP
    0 讨论(0)
  • 2021-01-05 07:21

    I wrote SRFI-41 which describes streams, provides an implementation, and gives many examples. The streams there differ from those in SICP, and are "better" in a way explained in the SRFI.

    0 讨论(0)
提交回复
热议问题