2013-04-03 17 views
2

我想根據對的權重 - 對中的兩個數字的總和來排序對的流。 (我不是不重複計算。)我的代碼似乎並不奏效有序流對 - 方案

(define (merge-weighted s1 s2 weight) 
    (let ((h1 (stream-car s1)) 
     (h2 (stream-car s2))) 
    (if ((weight h1) < (weight h2)) 
     (cons-stream h1 (merge-weighted (stream-cdr s1) s2 weight)) 
     (cons-stream h2 (merge-weighted new1 (stream-cdr s2) weight))))) 

與另一個整數流整數(S1)的流時調用合併加權(S2),並使用以下重量1:

(define (weight1 pair) 
    (+ (car pair) (cdr pair))) 

回答

0
(define (merge-weighted s1 s2 weight) 
(let ((h1 (stream-car s1)) 
    (h2 (stream-car s2))) 
(cond 
((null? s1) s2) 
((null? s2) s1) 
((< (weight h1) (weight h2)) 
     (cons-stream h1 (merge-weighted (stream-cdr s1) s2 weight))) 
(else 
     (cons-stream h2 (merge-weighted s1 (stream-cdr s2) weight))))) 

試試這一個。終止條件是我想的問題。

2

試試這個,它修復了一個錯位的<問題,增加了一些基礎的情況下處理空流:

(define (merge-weighted s1 s2 weight) 
    (cond ((stream-null? s1) s2) 
     ((stream-null? s2) s1) 
     (else 
     (let ((h1 (stream-car s1)) 
       (h2 (stream-car s2))) 
      (if (< (weight h1) (weight h2)) 
       (cons-stream h1 (merge-weighted (stream-cdr s1) s2 weight)) 
       (cons-stream h2 (merge-weighted s1 (stream-cdr s2) weight))))))) 

可以肯定,你應該張貼的問題與一個示例的一部分給定輸入的預期輸出。