[mercury-users] Polymorphism / Type classes

Ralph Becket rbeck at microsoft.com
Thu Jun 14 23:57:15 AEST 2001

> From: David Jeffery [mailto:dgj at cs.mu.OZ.AU]
> Sent: 14 June 2001 11:55
> [...]
> As it is written as the moment, the definition of do_useful quite 
> correctly gives a type error. This is because the type checker 
> needs to bind the type `U' to something, and ensure that this 
> type is in the useful type class. Given that the type variable 
> isn't bound to anything, we implicitly bind it to `void', and 
> there is no instance for useful(void).

Is there a simple explanation for why 2nd order polymorphism is

> How do you get around it? Two ways, and neither of them is terribly
> First, you can re-arrange your code so that the type that you call
> `do_stuff' with is bound at the point at which you call with_useful.
> always easy to do...


> :- typeclass foo(T) where [
> 	pred dummy(T, U, U) <= useful(U)
> ].
> ...and then you change your type class as follows:
> :- typeclass useful_factory(F) where
> 	[
> 		pred with_useful(T, F, F) <= foo(T),
> 		mode with_useful(in, di, uo) is det
> 	].
> :- type dummy1 ---> dummy1.
> :- instance foo(dummy1) where [
> 	dummy(_A, B, C) :- do_stuff(B, C)
> ].
> :- pred do_stuff(U, U) <= useful(U).
> :- mode do_stuff(di, uo) is det.
> do_stuff --> does lots of stuff.

Hooargh!  Will life always be like this?

If I write

:- typeclass a(A) where [ func f(all [B] func(B) = B <= b(B), A) = A ].

:- typeclass b(B) where [].

:- func g(T1) = T1 <= a(T1).
g(X) = f(h, X).

:- func h(T2) = T2 <= b(T2).
h(Y) = Y.

then I get all sorts of syntax errors on the definition for typeclass a.
Is this a 2nd order polymorphism thing?

I think we're going to need some very clear explanation of these points
if people are going to use typeclasses for fun and profit.  It all looks
so like it should work and it's frustrating not to have a clear picture
of where things went wrong!

- 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