灯下 登录
计算机科学 / SICP / 3.5.3 Exploiting the Stream Paradigm

Exercise 3.72 · 习题

Exercise 3.72: In a similar way to Exercise 3.71
generate a stream of all numbers that can be written as the sum of two
squares in three different ways (showing how they can be so written).

Streams as signals

We began our discussion of streams by describing them as computational analogs
of the “signals” in signal-processing systems. In fact, we can use streams
to model signal-processing systems in a very direct way, representing the
values of a signal at successive time intervals as consecutive elements of a
stream. For instance, we can implement an
integrator or

summer that, for an input stream x
=
(

x
i

), an initial
value C, and a small increment d
t, accumulates the sum
S
i

=

C
+

j
=
1

i

x
j

d
t
and returns the stream of values S
=
(

S
i

). The following
integral procedure is reminiscent of the “implicit style” definition
of the stream of integers (3.5.2):

(define (integral integrand initial-value dt)
(define int
(cons-stream
initial-value
(add-streams (scale-stream integrand dt)
int)))
int)

Figure 3.32 is a picture of a signal-processing system that corresponds
to the integral procedure. The input stream is scaled by d
t and
passed through an adder, whose output is passed back through the same adder.
The self-reference in the definition of int is reflected in the figure
by the feedback loop that connects the output of the adder to one of the
inputs.

SVG

Figure 3.32: The integral procedure viewed as a signal-processing system.

练习 3.72:用与练习 3.71 类似的方式,生成一个由所有能以三种不同方式写成两个平方数之和的数组成的流(并展示每种写法)。

流作为信号

我们在讨论流时,最初将其描述为信号处理系统中"信号 (signals)"的计算类比。事实上,我们可以用非常直接的方式用流来对信号处理系统建模:将信号在连续时间区间上的值表示为流中的连续元素。例如,我们可以实现一个积分器 (integrator) 或求和器 (summer):对于输入流 x = (xᵢ)、初始值 C 以及一个小增量 dt,它累积求和 Sᵢ = C + ∑(j=1 到 i) xⱼ dt,并返回值的流 S = (Sᵢ)。下面的 integral 过程令人联想到 3.5.2 中整数流的"隐式风格"定义:

(define (integral integrand initial-value dt)
(define int
(cons-stream
initial-value
(add-streams (scale-stream integrand dt)
int)))
int)

图 3.32 是与 integral 过程对应的信号处理系统图示。输入流被 dt 缩放后送入一个加法器,加法器的输出又被反馈回同一加法器的另一个输入端。int 定义中的自引用在图中体现为连接加法器输出与某一输入端的反馈回路。

SVG

图 3.32:将 integral 过程视为一个信号处理系统。

Racket #lang sicp
(define (integral integrand initial-value dt)
 (define int
 (cons-stream
 initial-value
 (add-streams (scale-stream integrand dt)
 int)))
 int)