灯下 登录
计算机科学 / SICP / 2.5.2 Combining Data of Different Types

Exercise 2.85 · 习题

Exercise 2.85: This section mentioned a method

for “simplifying” a data object by lowering it in the tower of types as far

as possible. Design a procedure drop that accomplishes this for the

tower described in Exercise 2.83. The key is to decide, in some general

way, whether an object can be lowered. For example, the complex number

1.5

+

0

i can be lowered as far as real, the complex number 1

+

0

i can

be lowered as far as integer, and the complex number 2

+

3

i cannot

be lowered at all. Here is a plan for determining whether an object can be

lowered: Begin by defining a generic operation project that “pushes”

an object down in the tower. For example, projecting a complex number would

involve throwing away the imaginary part. Then a number can be dropped if,

when we project it and raise the result back to the type we

started with, we end up with something equal to what we started with. Show how

to implement this idea in detail, by writing a drop procedure that drops

an object as far as possible. You will need to design the various projection

operations and

install project as a generic operation in the system. You will also

need to make use of a generic equality predicate, such as described in

Exercise 2.79. Finally, use drop to rewrite apply-generic

from Exercise 2.84 so that it “simplifies” its answers.

练习 2.85:本节提到了一种通过将数据对象在类型塔中尽可能向下降低来"化简"数据对象的方法。针对练习 2.83 所描述的类型塔,设计一个过程 drop 来实现这一目标。关键在于以某种通用的方式判断一个对象是否可以被降低。例如,复数 1.5 + 0i 最多可降至 real,复数 1 + 0i 最多可降至 integer,而复数 2 + 3i 则根本无法降低。以下是判断一个对象是否可以降低的方案:首先定义一个通用操作 project,将对象在塔中"下推"一步。例如,对复数作 project 操作就是丢弃其虚部。然后,若对一个数作 project 后再将结果 raise 回原来的类型,得到的结果与原始值相等,则该数可以被降低。请详细说明如何实现这一思路,写出能将对象尽可能降低的 drop 过程。你需要设计各种 projection 操作,并将 project 作为通用操作安装到系统中。你还需要使用一个通用相等谓词,如练习 2.79 所描述的那样。最后,用 drop 改写练习 2.84 中的 apply-generic,使其能"化简"计算结果。