<< Previous exercise (3.70) | Index | Next exercise (3.72) >>


 (define (Ramanujan s) 
          (define (stream-cadr s) (stream-car (stream-cdr s))) 
          (define (stream-cddr s) (stream-cdr (stream-cdr s))) 
          (let ((scar (stream-car s)) 
                    (scadr (stream-cadr s))) 
                 (if (= (sum-triple scar) (sum-triple scadr))  
                         (cons-stream (list (sum-triple scar) scar scadr) 
                                                  (Ramanujan (stream-cddr s))) 
                         (Ramanujan (stream-cdr s))))) 
 (define (triple x) (* x x x)) 
 (define (sum-triple x) (+ (triple (car x)) (triple (cadr x)))) 
 (define Ramanujan-numbers 
         (Ramanujan (weighted-pairs integers integers sum-triple))) 
 the next five numbers are: 
 (4104 (2 16) (9 15)) 
 (13832 (2 24) (18 20)) 
 (20683 (10 27) (19 24)) 
 (32832 (4 32) (18 30)) 
 (39312 (2 34) (15 33)) 


 (define ram-stream 
   (stream-map cadr  
               (stream-filter (lambda (x)(= (cube-weight (car x))(cadr x)))  
                  (stream-map list cube-stream (stream-cdr (stream-map cube-weight cube-stream)))))) 
 ;Wanted to do the exercise completely using stream paradigm. 


"Easy to understand" iterative version :-)

 (define (cubicSum  p) 
     (let ((i (car p)) 
           (j (cadr p))) 
       (+ (* i i i) (* j j j)))) 
 (define sortedStream (weighted-pairs cubicSum (integers 0) (integers 0))) 
 (define (ramanujan s pre) 
     (let (( num (cubicSum (stream-car s)))) 
       (cond ((= pre num) 
                         (ramanujan (stream-cdr s) num))) 
                     (ramanujan (stream-cdr s) num))))) 
 (display-stream (ramanujan sortedStream 0)) 


Small bug in meteorgan's solution: You don't want to apriori exclude the possibility of three consequent pairs all having the same weight...i.e. you dont want to recurse into the cddr in case you find a pair with equal weights, because (weight cadr) might be equal to (weight caddr)...

But this would give you the same number as the one you find with car and cadr. So we are safe to skip to cddr directly.