[Haskell-cafe] Idiomatic ways to make all instances of a certain class also instances of another?

Tim Cowlishaw tim at timcowlishaw.co.uk
Tue Jul 26 17:59:26 CEST 2011


Hi all,

I'm currently embarking on my first major project in Haskell, after
dabbling with it for several years, and seem to keep finding myself in
situations where I create a typeclass that seems to be some sort of
specialisation of another, more general typeclass. Given that this is
the case, I've then decided that all instances of the specific class
should therefore also be instances of the general class, and arrived
at the following method of doing so, using the FlexibleInstances and
UndecidableInstances extensions to GHC:

{-# LANGUAGE FlexibleInstances, UndecidableInstances #-}

class Max a where
  maximum :: a -> a -> a

instance (Ord a) => Max a where
  maximum = max


(Obviously, this is a very trivial, and rather silly example - I'm not
really trying to implement a class called 'Max').

However, I'd be curious to know if (a) There are better or more
idiomatic ways of achieving the same effect, and (b) Whether or not I
should be doing this at all; It did occur to me that this seems rather
trying to re-implement OOP-style inheritance with typeclasses, and
therefore perhaps not a very Haskellish approach to designing
software. Therefore - are there better ways to achieve this, or should
I not be doing this at all, and, if the latter, what would be the best
means of achieving a similar result (i.e. a typeclass that implements
all the functionality of one or more others, optionally with some
additional specialism)?

Many thanks,

Tim



More information about the Haskell-Cafe mailing list