SICP Practice

Practice 3.70

	(define (merge-weighted s1 s2 weight)
	  (cond ((stream-null? s1) s2)
	        ((stream-null? s2) s1)
	        (else
	          (let ((s1carweight (weight (stream-car s1)))
	                (s2carweight (weight (stream-car s2))))
	            (cond ((> s1carweight s2carweight) 
	                   (cons-stream (stream-car s2)
	                                (merge-weighted s1 (stream-cdr s2) weight)))
	                  ((< s1carweight s2carweight)
	                   (cons-stream (stream-car s1)
	                                (merge-weighted (stream-cdr s1) s2 weight)))
	                  (else
	                    (cons-stream (stream-car s1)
	                                 (cons-stream (stream-car s2)
	                                              (merge-weighted (stream-cdr s1) (stream-cdr s2) weight)))))))))

	(define (weighted-pairs s t weight)
	  (cons-stream (list (stream-car s) (stream-car t))
	               (merge-weighted
	                 (stream-map (lambda (x) (list (stream-car s) x))
	                             (stream-cdr t))
	                 (weighted-pairs (stream-cdr s)
	                                 (stream-cdr t)
	                                 weight)
	                 weight)))

a

	(define result-a
	  (define (weight x)
	    (let ((i (car x))
	          (j (cadr x)))
	      (+ i j)))
	  (weighted-pairs integers integers weight))

b

	(define result-b
	  (define (weight x)
	    (let ((i (car x))
	          (j (cadr x)))
	      (+ (* 2 i) (* 3 j) (* 5 i j))))

	  (define (div235 x)
	    (or (= 0 (remainder x 2))
	        (= 0 (remainder x 3))
	        (= 0 (remainder x 5))))

	  (let ((filtered-intgers (stream-filter div235 integers)))
	    (weighted-pairs filtered-integers filtered-integers weight)))