Ch.6 Introduction to ML programming

§ 6.6. Compound expressions and function definitions

Of course, constant, variables and primitive functions are not sufficient for writing a program that solves a complex problem. The important expressions in ML programming are those that represent functions.

As seen in an example in Section 6.2, a function is defined by the following syntax:

fun funName param = expr

After this declaration, the variable funName is bound to a function that takes param as its argument and returns the result computed by expr. For example, the equation for an arithmetic sequence we have seen before can be regarded as a function that takes a natural number n:


This definition can be programmed directly using fun as follows.

# fun S(n) = (n * (n + 1) * (2*n + 1)) div 6;
val S = fn : int -> int

After this definition, S can be used as follows.

# S 10;
val it = 385 : int
# S 20;
val it = 2870 : int