Triples procedure

Write a procedure triples that takes three infinite streams, S , T , and U , and produces the stream of triples (Si, Tj, Uk) such that i ≤ j ≤ k . Use triples to generate the stream of all Pythagorean triples of positive integers, i.e., the triples (i, j, k) such that i ≤ j and i² + j² = k² .

There are no comments yet.

Authentication required

You must log in to post a comment.

(define (stream-car stream) (car stream))

(define (stream-cdr stream) (force (cdr stream)))

(define (stream-ref s n)
  (if (= n 0)
      (stream-car s)
      (stream-ref (stream-cdr s) (- n 1))))

(define (interleave s1 s2)
  (if (stream-null? s1)
      (cons-stream (stream-car s1)
                   (interleave s2 (stream-cdr s1)))))

(define (stream-filter pred stream)
  (cond ((stream-null? stream) the-empty-stream)
        ((pred (stream-car stream))
         (cons-stream (stream-car stream)
                      (stream-filter pred
                                     (stream-cdr stream))))
        (else (stream-filter pred (stream-cdr stream)))))

(define (stream-map proc . list-of-stream)
    (if (null? (car list-of-stream))
            (apply proc 
                   (map (lambda (s)
                            (stream-car s))
            (apply stream-map 
                   (cons proc (map (lambda (s)
                                       (stream-cdr s))

(define (add-streams s1 s2)
  (stream-map + s1 s2))

(define (pairs s t)
   (list (stream-car s) (stream-car t))
    (stream-map (lambda (x) (list (stream-car s) x))
                (stream-cdr t))
    (pairs (stream-cdr s) (stream-cdr t)))))

(define ones (cons-stream 1 ones))

(define integers (cons-stream 1 (add-streams ones integers)))

(define s (triples integers integers integers))

(check-equal? (stream-ref s 0) '(1 1 1))
(check-equal? (stream-ref s 1) '(1 1 2))
(check-equal? (stream-ref s 2) '(2 2 2))
(check-equal? (stream-ref s 3) '(1 1 3))

(check-equal? (stream-ref pythagorian-triples 0) '(3 4 5))
(check-equal? (stream-ref pythagorian-triples 1) '(6 8 10))