Superclass Defaults

Ashley Yakeley ashley@semantic.org
Mon, 21 Jul 2003 06:21:33 -0700


This seems to be a frequently requested feature of Haskell: the ability 
to declare default members in a superclass for a particular class. 
Here's an example:

  class Functor f where
    fmap :: (a -> b) -> f a -> f b

  class (Functor f) => Monad f where
    ...

The idea is that it should be possible to declare a type an instance of 
both Monad and Functor without having to provide a definition for 
'fmap'. Instead, a default would be used:

  fmap ab fa = fa >>= (return . ab)

Well I don't doubt this would be a very useful extension to the Haskell 
language: indeed it would eliminate code in all my Haskell projects. But 
before we can propose this, we have to work out what the syntax would 
look like. Here are some properties I think such a mechanism should have:

  1. It should be possible to declare types as instances of
     Monad and Functor with a different definition of fmap
     overriding the default.

  2. It should be possible to declare another subclass of
     Functor that also has a default for fmap.

  3. The members of any existing class should be 
     subclass-defaultable in another module; i.e., no special
     syntax should be involved in the class declaration of
     the superclass.

  4. It should be possible to distinguish between different
     appearances of the same class in the superclass context.
     For instance:

     class C a where
        c :: Int -> a

     class (C a,C b,C (a -> b)) => D a b where
        ...

Any ideas?

-- 
Ashley Yakeley, Seattle WA