Ch.6 Introduction to ML programming

§ 6.2. Declarative programming

Functional programming is sometimes described as “declarative programming”. This is not a precise technical term. It somewhat vaguely suggests that programs naturally and directly express what they should realize. If the problem to be solved is procedural in nature then a procedural description may well be declarative. However, when the thing to be represented by a program has a well defined meaning, then declarative programming has more precise meaning.

When a program to be written is best understood as a function that takes an input and returns a result, then functional programming would be naturally declarative. As a simple example, consider the factorial function. The factorial of n, n!, is defined by the following mathematical equations.


In ML, it is coded below.

fun fact 0 = 1
     | fact n = n * fact (n - 1)

This declaration defines a function named fact. It consists of two cases separated by “|”. The first case says fact returns 1 if the parameter is 0, and the second case says it otherwise returns the multiple of n and the factorial of n - 1. These two cases exactly correspond to the mathematical definition of this function.

Various programs other than such a very simple mathematical function can be written in a concise and readable fashion if you can represent them as declarative functions according to the intended meaning. ML is a programming language that promotes this way of declarative programming. A key to master ML programming is to obtain a skill of writing declarative code in this sense. In the subsequent sections, we learn the essence of ML programming.