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

Claus Reinke claus.reinke at talk21.com
Mon Apr 27 18:31:58 EDT 2009

> 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.

Before going into language extensions, is there anything wrong with:

class C a where foo :: a -> Double

fooA a = 5.0 --default A
fooB a = 7.0 -- default B

data Blah = Blah
data Bar = Bar

instance C Blah where foo = fooA
instance C Bar  where foo = fooB

blah = Blah
bar = Bar

main = do
  print $ foo blah -- should print out 5
  print $ foo bar  -- should print out 7

It seems to match your spec.


More information about the Haskell-Cafe mailing list