Next: Instance declarations, Up: Type classes [Contents]
A type class is a name for a set of types (or a set of sequences of types) for which certain predicates and/or functions, called the methods of that type class, are defined. A ‘typeclass’ declaration defines a new type class, and specifies the set of predicates and/or functions that must be defined on a type (or sequence of types) for it (them) to be considered to be an instance of that type class.
The typeclass
declaration
gives the name of the type class that it is defining,
the names of the type variables which are parameters to the type class,
and the operations (i.e. methods) which form the interface of the type class.
For each method, all parameters of the typeclass must be determined by
the type variables appearing in the type signature of the method.
A variable is determined by a type signature
if it appears in the type signature,
but if functional dependencies are present,
then it may also be determined from the other variables
(see Functional dependencies).
For example,
:- typeclass point(T) where [ % coords(Point, X, Y): % X and Y are the cartesian coordinates of Point pred coords(T, float, float), mode coords(in, out, out) is det, % translate(Point, X_Offset, Y_Offset) = NewPoint: % NewPoint is Point translated X_Offset units in the X direction % and Y_Offset units in the Y direction func translate(T, float, float) = T ].
declares the type class point
,
which represents points in two dimensional space.
pred
, func
and mode
declarations
are the only legal declarations inside a typeclass
declaration.
The mode and determinism of type class methods
must be explicitly declared or (for functions) defaulted, not inferred.
In other words, for each predicate declared in a type class,
there must be at least one mode declaration,
and each mode declaration in a type class
must include an explicit determinism annotation.
Functions with no explicit mode declaration
get the usual default mode (see Modes):
all arguments have mode in
, the result has mode out
,
and the determinism is det
.
The number of parameters to the type class (e.g. T
) is not limited.
For example, the following is allowed:
:- typeclass a(T1, T2) where […].
The parameters must be distinct variables.
Each typeclass
declaration must have at least one parameter.
It is legal for a typeclass
declaration to declare no methods,
for example
:- typeclass foo(T) where [].
There must not be more than one type class declaration with the same name and arity in the same module.
Next: Instance declarations, Up: Type classes [Contents]