In the previous section, we saw how to design systems in which data objects can
be represented in more than one way. The key idea is to link the code that
specifies the data operations to the several representations by means of
generic interface procedures. Now we will see how to use this same idea not
only to define operations that are generic over different representations but
also to define operations that are generic over different kinds of arguments.
We have already seen several different packages of arithmetic operations: the
primitive arithmetic (+, -, *, /) built into our
language, the rational-number arithmetic (add-rat, sub-rat,
mul-rat, div-rat) of 2.1.1, and the complex-number
arithmetic that we implemented in 2.4.3. We will now use
data-directed techniques to construct a package of arithmetic operations that
incorporates all the arithmetic packages we have already constructed.
在上一节中,我们看到了如何设计数据对象可以以多种方式表示的系统。其关键思想是:通过通用接口过程 (generic interface procedures),将规定数据操作的代码与若干不同的表示联系起来。现在我们将看到,同样的思想不仅可以用于定义对不同表示通用的操作,还可以用于定义对不同类型的参数通用的操作。我们已经见过几个不同的算术运算包:内建于语言中的基本算术(`+`、`-`、`*`、`/`),2.1.1 节中的有理数算术(`add-rat`、`sub-rat`、`mul-rat`、`div-rat`),以及我们在 2.4.3 节中实现的复数算术。现在我们将使用数据导向技术,构造一个将所有这些已有算术包融为一体的算术运算包。
Figure 2.23 shows the structure of the system we shall build. Notice the
abstraction barriers. From the perspective of someone using “numbers,” there
is a single procedure add that operates on whatever numbers are
supplied. Add is part of a generic interface that allows the separate
ordinary-arithmetic, rational-arithmetic, and complex-arithmetic packages to be
accessed uniformly by programs that use numbers. Any individual arithmetic
package (such as the complex package) may itself be accessed through generic
procedures (such as add-complex) that combine packages designed for
different representations (such as rectangular and polar). Moreover, the
structure of the system is additive, so that one can design the individual
arithmetic packages separately and combine them to produce a generic arithmetic
system.
Figure 2.23: Generic arithmetic system.
图 2.23 展示了我们将要构建的系统结构。注意其中的抽象屏障。从使用"数"的人的角度来看,存在一个统一的过程 `add`,它能操作所提供的任何数。`add` 是通用接口的组成部分,该接口使独立的普通算术包、有理数算术包和复数算术包都能被使用数的程序统一访问。任何单独的算术包(例如复数包)本身也可以通过通用过程(例如 `add-complex`)来访问,这些通用过程组合了为不同表示(例如直角坐标和极坐标)设计的包。此外,该系统的结构是可加的,因此可以分别设计各个算术包,再将它们组合成一个通用算术系统。
图 2.23:通用算术系统。