NEXT ·  UP ·  PREVIOUS ·  CONTENTS ·  INDEX

Function types and type abbreviations

On rare occasions, we need to tell Standard ML the type of a function parameter which it cannot itself infer. If we have to do that then it is convenient to be able to give a name to the type, rather than including the expression for the type in a constraint on a parameter. One time when we need to specify a type is when we write a function which projects information from a record. The following function is not an acceptable Standard ML function.

fun initials p = (#initial p, String.sub(#surname p, 0));

The problem is that the type of the parameter p is underdetermined. We can see that it must be a record type with fields for initial letter and surname but what other fields does it have? Does it have age? Does it have date_of_birth? We cannot tell from the function definition and Standard ML does not support a notion of subtyping. No relation holds between tuples which are not identical: int * real * bool and int * real are not related. This has the consequence that it is impossible to define a function such as the function above without making explicit the type of the parameter, which we now do with the help of a type abbreviation.

type person = { initial : char, surname : string, age : int };

fun initials (p : person) = (#initial p, String.sub(#surname p, 0));

Type abbreviations are purely cosmetic. The type name person simply serves as a convenient abbreviation for the record type expression involving initial, surname and age.

As another example of the use of a type abbreviation, consider the possibility of representing sets by functions from the type of the elements of the set to the booleans. These functions have the obvious behaviour that the function returns true when applied to an element of the set and false otherwise. If we are using functions in this way it would be reasonable to expect to be able to state the fact that these functions represent sets. The complication here is that a family of type abbreviations are being defined; integer sets, real sets, word sets, boolean sets and others. One or more type variables may be used to parameterise a type abbreviation, as shown below.

type 'a set = 'a -> bool;

Type variables such as 'a, 'b, 'c, are pronounced `alpha', `beta', `gamma'.

NEXT ·  UP ·  PREVIOUS ·  CONTENTS ·  INDEX