[mercury-users] Extending a structure data type in Mercury

Ralph Becket rafe at cs.mu.OZ.AU
Wed Jul 6 11:34:20 AEST 2005

Gregory D. Weber, Tuesday,  5 July 2005:
> (Thanks for your response; I've been away; it's nice to be getting back to Mercury.)
> I did consider using typeclasses.  If I understand correctly,
> typeclasses are like interfaces in Java,

That's about right: type classes and Java interfaces have much in

> so I would have to
> declare a type class with some methods, then define
> instances ("classes"?) which implement those methods.


> I can't have one typeclass be a subclass of another
> and inherit methods from it, can I?

You can declare hierarchies of type classes, for example:

:- typeclass point(T) where [
	func x(T) = int,
	func y(T) = int

:- typeclass coloured_point(T) <= point(T) where [
	func rgb(T) = {int, int, int}

Here, an type that is an instance of coloured_point is also required to
be an instance of point.  You can pass a coloured_point instance
whereever a point instance is expected:

:- type xy == {int, int}.

:- instance point(xy) where [
	x({X, _}) = X,
	y({_, Y}) = Y

:- type xy_rgb == {int, int, {int, int, int}}.

:- instance point(xy_rgb) where [
	x({X, _, _}) = X,
	y({_, Y, _}) = Y

:- instance coloured_point(xy_rgb) where [
	rgb({_, _, RGB}) = RGB

:- pred print_point(T::in, io::di, io::uo) <= point(T) is det.

print_point(P, !IO) :-
	io.format("(%d, %d)", [i(x(P)), i(y(P))], !IO).

print_point/3 will also accept instances of coloured_point because every
coloured_point is also a point.

> So if I were to do this with type classes, I would need to think of
> prules, etc., as abstract data types; the type class would declare
> methods like prule_key, prule_class, prule_ftable, prule_conds, and
> the instances cn2rule and icnrule would each have to define
> implementations of those methods.  Correct?

That's right.

-- Ralph
mercury-users mailing list
post:  mercury-users at cs.mu.oz.au
administrative address: owner-mercury-users at cs.mu.oz.au
unsubscribe: Address: mercury-users-request at cs.mu.oz.au Message: unsubscribe
subscribe:   Address: mercury-users-request at cs.mu.oz.au Message: subscribe

More information about the users mailing list