[Haskell-cafe] Can subclass override its super-class' default implementation of a function?

Ryan Ingram ryani.spam at gmail.com
Mon Apr 27 17:17:54 EDT 2009

No, but functionality similar to this has been proposed several times,
under the name "Class Aliases" [1].

The big problem is in the definition of B:
   class (A a) => B a where ...

In this case, you must make something an instance of A before it can
be an instance of B, and, in order to make something an instance of A,
you must provide an implementation of "foo".  Not providing an
implementation is the same as providing the default.

With the class alias proposal you would write

> class B a = A a where
>    foo a = 7.0

In this case, (B a) and (A a) are the same class, but provide
different default implementations for the methods.  So you *cannot*
declare something an instance of both B and A.  But if you declare
something an instance of B without providing an implementation of
"foo", it would use B's default, whereas instances of A would use A's

Unfortunately, I don't believe anyone is working on implementing this
proposal.  It's high on my list of "desired features", but I think
that not all the details have been figured out with how it interacts
with other features of the language.

  -- ryan

[1] http://repetae.net/recent/out/classalias.html,

On Mon, Apr 27, 2009 at 2:00 PM, siki <gabor at karamaan.com> wrote:
> I'm not sure if this is possible at all. I'd like to do something like this:
> class A a where
>    foo :: a -> Double
>    foo a = 5.0
> class (A a) => B a where
>    foo a = 7.0
> data Blah = Blah
> data Bar = Bar
> instance A Blah
> instance B Bar
> let blah = Blah
>    bar = Bar
> foo blah -- should print out 5
> foo bar  -- should print out 7
> Basically, I have a bunch of instances that have a common functionality but
> I'd like to be able to group those instances and give each group a different
> default implementation of that functionality. It's so easy to do this in
> Java, for example, but I have no idea how to do it in Haskell. The above
> example will not compile, btw.
> Thanks a lot
> --
> View this message in context: http://www.nabble.com/Can-subclass-override-its-super-class%27-default-implementation-of-a-function--tp23264975p23264975.html
> Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com.
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe

More information about the Haskell-Cafe mailing list