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)))))

当使用另一个整数流 (s2) 对整数流 (s1) 调用合并加权并使用以下 weight1 时:

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

2 回答 2

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)))))))

可以肯定的是,您应该在问题中发布一个示例,其中包含给定输入的预期输出。

于 2013-04-03T14:31:50.117 回答
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)))))

试试这个。终止条件是我认为的问题。

于 2013-04-03T13:31:33.207 回答