[mercury-users] Type Classes: can instance implementations be methods?

Maria Garcia de la Banda mbanda at mail.csse.monash.edu.au
Wed Jan 29 09:47:59 AEDT 2003


I am wondering whether the method definition in an instance declaration can
in fact be a method in the same (or some other) type class. The reason I
want this is because in the context of the HAL language (which is compiled
into Mercury) we support default methods (which are implemented by a given
default predicate but can be overwritten by any instance) and sometimes the
best implementation for a default method is another method. For example,
assume we have a class solver(X) (interface for a constraint solver) which
has, among others, the methods init(X) and maybe_init(X). The former
initialises a constraint variable X, while the latter will usually also
initialise a constraint variable but can also perform a dummy
initialisation for types in which such initialisation can be optimised
away. Then, maybe_init(X) can be defined by default as init(X) except for
the instances in which a dummy predicate is allowed, for which a dummy
method will overwrite the default.

This is easily defined in Mercury as

:- typeclass solver(X) where [
    impure pred init(X::out) is det,
    impure pred maybe_init(X::out) is det].

:- instance(mytype) where [
    pred(init/2) is init_mytype,
    pred(maybe_init/2) is init].

Yes, I could modify the HAL compiler so that it looked for the actual
implementation of the method, resulting in

:- instance(mytype) where [
    pred(init/2) is init_mytype,
    pred(maybe_init/2) is init_mytype].

but the first approach is simpler.

Now, I have tried this in Mercury and gives me no trouble. However, I then
thought that one can also easily define loops among the definitions like:

:- instance(mytype) where [
    pred(init/2) is maybe_init,
    pred(maybe_init/2) is init].

and this also passes Mercury's compilation, so now I am wondering whether
the instance definition passes compilation because it is allowed (but the
test for looped-definitions was forgotten) or because this posibility was
not even considered by the compiler.



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