Ch.6 Introduction to ML programming

§ 6.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 1. n * fact (n - 1) is an expression involving variable n and function application. The basic principle of ML programming is

programming is done by defining an expression that represents the desired value.

An expression consist of the following components:

  1. constants such as 1,

  2. variables representing function parameters and defined values.

  3. function applications (function calls), and

  4. 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 Sn=12+22++n2 is given by the following equation.

Sn=n(n+1)(2n+1)6

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 n is defined, it correctly computes Sn as seen below.

# val n = 10;
val n = 10 : int
val Sn = (n * (n + 1) * (2*n + 1)) div 6;
val Sn = 385 : int