Я пытаюсь понять, как работает эта функция.
(define (sieve stream)
(cons-stream
(stream-car stream)
(sieve (stream-filter
(lambda (x)
(not (divisible? x (stream-car stream))))
(stream-cdr stream)))))
(define primes (sieve (integers-starting-from 2)))
Просто, я использую поток, который генерирует все целые числа, начиная с 2, и, согласно книге, он фильтрует остальную часть потока, которая не делится на текущий элемент, для каждого нового элемента. Как это может отфильтровать все целые числа, не кратные текущему элементу без фактического чтения всех целых чисел?
Эти определения
(define (sieve stream)
(cons-stream (stream-car stream)
(sieve
(stream-filter (lambda (x) (not (divisible? x (stream-car stream))))
(stream-cdr stream)))))
(define primes (sieve (integers-starting-from 2)))
означают, что
primes
=
(sieve
(integers-starting-from 2))
=
(cons-stream 2
(sieve
(stream-filter (lambda (x) (not (divisible? x 2)))
(integers-starting-from 3))))
=
(cons-stream 2
(cons-stream 3
(sieve
(stream-filter (lambda (x) (not (divisible? x 3)))
(stream-filter (lambda (x) (not (divisible? x 2)))
(integers-starting-from 4))))))
=
(cons-stream 2
(cons-stream 3
(sieve
(stream-filter (lambda (x) (not (divisible? x 3)))
(stream-filter (lambda (x) (not (divisible? x 2)))
(integers-starting-from 5))))))
=
(cons-stream 2
(cons-stream 3
(cons-stream 5
(sieve
(stream-filter (lambda (x) (not (divisible? x 5)))
(stream-filter (lambda (x) (not (divisible? x 3)))
(stream-filter (lambda (x) (not (divisible? x 2)))
(integers-starting-from 6))))))))
и далее
=
....
=
(cons-stream 2
(cons-stream 3
(cons-stream 5
(cons-stream 7
(sieve
(stream-filter (lambda (x) (not (divisible? x 7)))
(stream-filter (lambda (x) (not (divisible? x 5)))
(stream-filter (lambda (x) (not (divisible? x 3)))
(stream-filter (lambda (x) (not (divisible? x 2)))
(integers-starting-from 9))))))))))
=
....
=
(cons-stream 2
(cons-stream 3
(cons-stream 5
(cons-stream 7
(cons-stream 11
(sieve
(stream-filter (lambda (x) (not (divisible? x 11)))
(stream-filter (lambda (x) (not (divisible? x 7)))
(stream-filter (lambda (x) (not (divisible? x 5)))
(stream-filter (lambda (x) (not (divisible? x 3)))
(stream-filter (lambda (x) (not (divisible? x 2)))
(integers-starting-from 12))))))))))))
=
....
что, надеюсь, должно дать вам более четкое представление о том, что здесь происходит.
(NB: последующая запись ).