Endless Upward Sequence in Racket

Is there a Python itertools.count in Racket? I want to create an endless stream of evenly distributed numbers. in-naturals seems like what I want, but does not provide a step. I would like not to reinvent the wheel, but if there is no equivalent function, how to write it? (suppose generators should be used)

+4
source share
2 answers

You can get the same Python count functionality using in-range with infinite end value:

 (define (count start step) (in-range start +inf.0 step)) 

For instance:

 (define s (count 2.5 0.5)) (stream-ref s 0) => 2.5 (stream-ref s 1) => 3.0 (stream-ref s 2) => 3.5 (stream-ref s 3) => 4.0 
+6
source

The execution of the function itself can be performed on one line:

 (define (stream-from ns) (stream-cons n (stream-from (+ ns) s))) 

To test this, you are here an example that prints 100,000 numbers:

 #lang racket (require racket/stream) (define (stream-from ns) (stream-cons n (stream-from (+ ns) s))) (define (stream-while sp) (let ([fst (stream-first s)]) (if (p fst) (stream-cons fst (stream-while (stream-rest s) p)) empty-stream))) (define test (stream-while (stream-from 0 1) (Ξ» (x) (< x 100000)))) (stream-for-each println test) 
+1
source

All Articles