灯下 登录
计算机科学 / SICP / 1.3.1 Procedures as Arguments

Exercise 1.33 · 习题

Exercise 1.33: You can obtain an even more
general version of accumulate (Exercise 1.32) by introducing the
notion of a
filter on the terms to be combined. That is, combine
only those terms derived from values in the range that satisfy a specified
condition. The resulting filtered-accumulate abstraction takes the same
arguments as accumulate, together with an additional predicate of one argument
that specifies the filter. Write filtered-accumulate as a procedure.
Show how to express the following using filtered-accumulate:

the sum of the squares of the prime numbers in the interval a to b
(assuming that you have a prime? predicate already written)

the product of all the positive integers less than n that are relatively
prime to n (i.e., all positive integers i

n such that

GCD

(

i

,

n

)

=

1).

练习 1.33:通过对待组合的项引入过滤器 (filter) 的概念,可以得到 accumulate(练习 1.32)的一个更一般的版本——只组合那些由满足指定条件的区间内的值导出的项。由此得到的 filtered-accumulate 抽象与 accumulate 具有相同的参数,并额外接受一个单参数谓词来指定过滤条件。将 filtered-accumulate 写成一个过程,并说明如何用 filtered-accumulate 表达以下内容:

区间 a 到 b 内所有素数的平方和(假设你已经写好了谓词 prime?)

所有小于 n 且与 n 互素的正整数之积(即所有满足 GCD(i, n) = 1 的正整数 i < n 之积)。