How can I define integers through stream-map in Scheme:
(define integers (stream-cons 1 (stream-map *something* *something*))
(define integers
(stream-cons 1
(stream-map add1 integers)))
See SRFI-41 for more about streams.
The answer by @user448810 is perfect and it will work in Racket (it uses Racket-specific procedures). But the question is also tagged with SICP
, so here is my two cents.
Answering the question with only the subset of Scheme's procedures available in SICP yields an equivalent but slightly different solution, using only the following primitive stream operations defined in the book: stream-null? stream-cons stream-car stream-cdr
. In particular, notice that stream-map
is not a standard part of Scheme, and in the book it was implemented in terms of primitive operations, with an advantage over Racket's implementation - it can receive a variable number of streams as parameters:
(define (stream-map proc . args)
(if (stream-null? (car args))
stream-null
(stream-cons (apply proc (map stream-car args))
(apply stream-map (cons proc (map stream-cdr args))))))
(define (add-streams s1 s2)
(stream-map + s1 s2))
With the above procedures in place, it's easy to define integers
(define ones (stream-cons 1
ones))
(define integers (stream-cons 1
(add-streams ones integers)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With