Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Streams in Scheme - define integers through stream map in scheme

How can I define integers through stream-map in Scheme:

(define integers (stream-cons 1 (stream-map *something* *something*))
like image 558
nanachan Avatar asked Jan 24 '13 15:01

nanachan


2 Answers

(define integers
  (stream-cons 1
    (stream-map add1 integers)))

See SRFI-41 for more about streams.

like image 93
user448810 Avatar answered Nov 15 '22 08:11

user448810


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)))
like image 22
Óscar López Avatar answered Nov 15 '22 08:11

Óscar López