Exercise 3.70: It would be nice to be able to
generate streams in which the pairs appear in some useful order, rather than in
the order that results from an ad hoc interleaving process. We can use
a technique similar to the merge procedure of Exercise 3.56, if we
define a way to say that one pair of integers is “less than” another. One
way to do this is to define a “weighting function” W
(
i
,
j
) and
stipulate that (
i
1
,
j
1
) is less than (
i
2
,
j
2
) if
W
(
i
1
,
j
1
)
W
(
i
2
,
j
2
). Write a procedure
merge-weighted that is like merge, except that
merge-weighted takes an additional argument weight, which is a
procedure that computes the weight of a pair, and is used to determine the
order in which elements should appear in the resulting merged
stream. Using this, generalize pairs to a procedure
weighted-pairs that takes two streams, together with a procedure that
computes a weighting function, and generates the stream of pairs, ordered
according to weight. Use your procedure to generate
the stream of all pairs of positive integers (
i
,
j
) with i
≤
j
ordered according to the sum i
+
j,
the stream of all pairs of positive integers (
i
,
j
) with i
≤
j,
where neither i nor j is divisible by 2, 3, or 5, and the pairs are
ordered according to the sum 2
i
+
3
j
+
5
i
j.
练习 3.70:如果能以某种有用的顺序生成序对构成的流,而不是依赖某种临时的交织过程所产生的顺序,那将会很方便。我们可以借鉴练习 3.56 中 merge 过程所用的技术,只要定义一种方式来说明一个整数序对"小于"另一个序对。一种方法是定义一个"权函数 (weighting function)" W(i, j),并规定若 W(i₁, j₁) < W(i₂, j₂),则 (i₁, j₁) 小于 (i₂, j₂)。请写一个过程 merge-weighted,它与 merge 类似,但 merge-weighted 多接受一个参数 weight——该参数是一个计算序对权值的过程,用于确定各元素在合并后的流中出现的顺序。在此基础上,将 pairs 推广为一个过程 weighted-pairs,它接受两个流以及一个计算权函数的过程,并生成按权值排序的序对流。用你的过程生成:所有正整数序对 (i, j)(其中 i ≤ j),按 i + j 之和排序的流;所有正整数序对 (i, j)(其中 i ≤ j,且 i 和 j 均不能被 2、3 或 5 整除),按 2i + 3j + 5ij 之和排序的流。