我正在尝试根据对的权重来命令对的流 - 对中两个数字的总和。 (我不排除重复。)我的代码似乎没有工作
(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)上调用merge-weighted与另一个整数流(s2)并使用以下weight1:
(define (weight1 pair)
(+ (car pair) (cdr pair)))
答案 0 :(得分: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)))))))
可以肯定的是,您应该在问题的一部分发布一个给定输入的预期输出的示例。
答案 1 :(得分: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)))))
试试这个。终止条件是我认为的问题。