Code Review

Compare your solutions

    #| BEGIN (Write your solution here) |#
(define (merge-weighted weight s1 s2)
  (cond ((stream-null? s1) s2)
        ((stream-null? s2) s1)
        (else
         (let ((s1car (stream-car s1))
               (s2car (stream-car s2)))
           (let ((s1weight (weight s1car))
                 (s2weight (weight s2car)))
             (cond ((< s1weight s2weight)
                    (cons-stream s1car (merge-weighted weight (stream-cdr s1) s2)))
                   ((> s1weight s2weight)
                    (cons-stream s2car (merge-weighted weight s1 (stream-cdr s2))))
                   (else
                    (cons-stream s1car
                                 (cons-stream s2car
                                              (merge-weighted weight
                                                              (stream-cdr s1)
                                                              (stream-cdr s2)))))))))))
(define (weight-pairs s t weight)
  (define weightproc
    (lambda (pair)
      (weight (car pair) (cdr pair))))
  (cons-stream
   (cons (stream-car s) (stream-car t))
   (merge-weighted weightproc
                   (stream-map (lambda (x) (cons (stream-car s) x))
                               (stream-cdr t))
                   (weight-pairs (stream-cdr s) (stream-cdr t) weight))))

(define (cube x) (* x x x))

(define cube-pairs
  (weight-pairs integers integers
                (lambda (i j) (+ (cube i) (cube j)))))

(show-stream cube-pairs 2)

(define (extract-ramanujan pairs weightproc)
  (let ((p1 (stream-car pairs))
        (p2 (stream-car (stream-cdr pairs))))
    (if (= (weightproc p1) (weightproc p2))
        (cons-stream
         (weightproc p1)
         (extract-ramanujan (stream-cdr pairs) weightproc))
        (extract-ramanujan (stream-cdr pairs) weightproc))))

(define ramanujan-numbers
  (extract-ramanujan cube-pairs
                     (lambda (pair) (+ (cube (car pair))
                                       (cube (cdr pair))))))
#| END |#