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

Henning Thielemann lemming at henning-thielemann.de
Wed Jul 27 00:31:58 CEST 2011


On Tue, 26 Jul 2011, Tim Cowlishaw wrote:

> For instance, for a typeclass representing the interface that any
> Order type should implement:
>
> class Order o where
>  price :: o -> Int
>  size :: o -> Int
>
> I'd like to be able to specify an Eq instance for all types of class
> Order in a manner similar to this:
>
> instance (Order o) => Eq o where
>  o1 == o2 = (price o1 == price o2) && (size o1 == size o2)

You may define once:

orderEq :: Order o => o -> o -> Bool
orderEq o1 o2 = (price o1 == price o2) && (size o1 == size o2)

and then define instances like

instance Order A where ...
instance Eq A where (==) = orderEq

instance Order B where ...
instance Eq B where (==) = orderEq


I don't think there is an easier and still predictable way of defining the 
Eq instances.



More information about the Haskell-Cafe mailing list