Next: , Previous: Abstract instance declarations, Up: Type classes   [Contents]


10.5 Type class constraints on predicates and functions

Mercury allows a type class constraint to appear as part of a predicate or function’s type signature. This constrains the values that can be taken by type variables in the signature to belong to particular type classes.

A type class constraint has the form:

<= Typeclass(Type, …), …

where Typeclass is the name of a type class and Type is a type. Any variable that appears in Type must be determined by the predicate’s or function’s type signature. 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 other variables (see Functional dependencies). Each type class constraint in a predicate or function declaration must contain at least one variable.

For example

:- pred distance(P1, P2, float) <= (point(P1), point(P2)).
:- mode distance(in, in, out) is det.

distance(A, B, Distance) :-
    coords(A, Xa, Ya),
    coords(B, Xb, Yb),
    XDist = Xa - Xb,
    YDist = Ya - Yb,
    Distance = sqrt(XDist*XDist + YDist*YDist).

In the above example, the distance predicate is able to calculate the distance between any two points, regardless of their representation, as long as the coords operation has been defined. These constraints are checked at compile time.