Version 9 (modified by john@…, 13 years ago) (diff)

Class Method Types

Brief Explanation

In Haskell 98, s4.3.1, the signatures of methods in a class may contain constraints, but these constraints must not mention the argument of the type class. The following is illegal:

class Foo a where
    op :: Num a => a -> a -> a

The motivation was perhaps that without such constraints, class dictionaries could be represented as records with PolymorphicComponents.

However this restriction is not implemented by Hugs, following a suggestion of Mark Jones in Typing Haskell in Haskell, and can be turned off in GHC with -fglasgow-exts.

interaction with existentials

If this were allowed than existential types of the form

data SomeFoo = exists a . Foo a => SomeFoo a

would have to carry around a dictionary for Num as well as Foo in dictionary passing implementation of type classes. In general some sort of fixpoint iteration would be needed to determine the set of dictionaries needed on an existential type. other choices would be to disallow existential types of such classes, disallow calling of methods with such constraints on an existential, or require the user specify a full list of needed classes in the data type (ruling out the ability to create existentials of things that are Foos but not Nums).

Even if this were done there would be no way to _statically_ tell if an existential will be filled with something of type Num, so a runtime error would have to be used when it isn't. Basically, we would have to conjure a dictionary full of bottoms for Num out of thin air.

Typecase based implementations of classes such as jhcs do not have a problem with classes or existentials of this form since all classes are determined from the single type parameter no matter how many classes are actually needed.


Can someone submit some real world examples of where this would be useful?



relax restriction on signatures of class methods