Though it is very simple, sum_squares exemplifies the most powerful property of user-defined functions. The function sum_squares is defined in terms of the function square, but relies only on the relationship that square defines between its input arguments and its output values.
尽管非常简单,sum_squares还是展示了用户定义函数最强大的特性。sum_squares函数是根据函数square定义的,但它只依赖于square定义的输入参数和输出值之间的关系。
We can write sum_squares without concerning ourselves with how to square a number. The details of how the square is computed can be suppressed, to be considered at a later time. Indeed, as far as sum_squares is concerned, square is not a particular function body, but rather an abstraction of a function, a so-called functional abstraction. At this level of abstraction, any function that computes the square is equally good.
我们可以写sum_squares,而不用考虑如何求一个数的平方。如何计算平方的细节可以省略,稍后再考虑。事实上,就sum_squares而言,square不是一个特定的函数体,而是一个函数的抽象,即所谓的函数抽象。在这个抽象层次上,任何计算平方的函数都是等价的。
Thus, considering only the values they return, the following two functions for squaring a number should be indistinguishable. Each takes a numerical argument and produces the square of that number as the value.
因此,只考虑它们返回的值,下面两个求平方的函数应该是难以区分的。每个都接受一个数字参数,并产生该数字的平方作为值。
>>> def square(x):
return mul(x, x)
>>> def square(x):
return mul(x, x-1) + x
In other words, a function definition should be able to suppress details. The users of the function may not have written the function themselves, but may have obtained it from another programmer as a “black box”. A programmer should not need to know how the function is implemented in order to use it. The Python Library has this property. Many developers use the functions defined there, but few ever inspect their implementation.
换句话说,函数定义应该能够隐藏细节。该函数的用户可能并没有自己编写该函数,但可能是作为“黑盒”从另一个程序员那里获得的。程序员不需要知道函数是如何实现的就可以使用它。Python库就有这个属性。许多开发人员使用那里定义的函数,但是很少有人检查它们的实现。
Aspects of a functional abstraction. To master the use of a functional abstraction, it is often useful to consider its three core attributes. The domain of a function is the set of arguments it can take. The range of a function is the set of values it can return. The intent of a function is the relationship it computes between inputs and output (as well as any side effects it might generate). Understanding functional abstractions via their domain, range, and intent is critical to using them correctly in a complex program.
For example, any square function that we use to implement sum_squares should have these attributes:
函数抽象的各个方面。为了掌握函数抽象的使用,考虑它的三个核心属性通常是有用的。函数的域是它可以接受的一组参数。函数的范围是它可以返回的一组值。函数的mu目的是它计算的输入和输出之间的关系(以及它可能产生的任何副作用)。通过领域、范围和意图理解功能抽象对于在复杂程序中正确使用它们是至关重要的。 例如,我们用来实现sum_squares的任何square函数都应该具有以下属性:
- The domain is any single real number.
- The range is any non-negative real number.
- The intent is that the output is the square of the input.
- 域是任意一个实数。
- 范围是任何非负实数。
- 目的是输出是输入的平方。
These attributes do not specify how the intent is carried out; that detail is abstracted away.
这些属性没有指定目的是如何实现的;这个细节被抽象掉了。