Вопрос

Is there an analog of Python's itertools.count in Racket? I want to create an infinite stream of evenly spaced numbers. in-naturals is similar to what i want, but does not provide step. I'd want not to reinvent the wheel, but if there's no equivalent function, how to write one? (i presume, generators should be used)

Это было полезно?

Решение

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

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

For example:

(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

Другие советы

Making the function yourself can be done in a single line:

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

To test it, you here is an example that prints 100000 numbers:

#lang racket
(require racket/stream)

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

(define (stream-while s p)
  (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)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top