§ 3.3. Representing computation by composing expressions
In the factorial example, the program returns 1
if the parameter is 0,and returns n * fact (n - 1)
otherwise.
In this way, the value returned by a function is represented by
an expression.
1 in the first case is an expression representing the
natural number
programming is done by defining an expression that represents the desired value.
An expression consist of the following components:
-
constants such as 1,
-
variables representing function parameters and defined values.
-
function applications (function calls), and
-
functions and other data structure constructions
The items 1 through 3 are the same as in mathematical expressions,
we have leaned in school.
For example, the sum of the arithmetic sequence
This is directly programmed as follows.
val Sn = (n * (n + 1) * (2*n + 1)) div 6
* and div are integer multiplication and division,
respectively.
When
# val n = 10;
val n = 10 : int
val Sn = (n * (n + 1) * (2*n + 1)) div 6;
val Sn = 385 : int