Defining methods generically for a class

I have the following class: class Region a where numDimensions :: a -> Int dim :: Int -> a -> (Double,Double) merge :: a -> a -> a and several ancillary methods defined, the most importance of which is: bounds :: Region a => a -> [(Double,Double)] bounds r = take (numDimensions r) . map dim . iterate (+1) $ 0 Let's say that I want all Regions to also be of class Eq, where regiona == regionb = all $ zipWith (==) (bounds regiona) (bounds regionb) How do I declare all Regions to be Eqs without putting it in the class body (since I define a function over all Regions that is independent of datatype that is an instance of Region)? Is it merely: instance Region a => Eq a where regiona == regionb = all $ zipWith (==) (bounds regiona) (bounds regionb) -- Jeff

On Thu, Jan 8, 2009 at 6:04 PM, Jeff Heard
... How do I declare all Regions to be Eqs without putting it in the class body (since I define a function over all Regions that is independent of datatype that is an instance of Region)?
Would this be a solution? class Eq a => Region a where ... Cristiano

Hi Jeff, Jeff Heard wrote:
instance Region a => Eq a where regiona == regionb = all $ zipWith (==) (bounds regiona) (bounds regionb)
If you want to be Haskell98 compliant, why not define regionEquals :: Region a => a -> a -> Bool as above and use that everywhere instead of (==)? If you insist on using the overloaded (==), then in Haskell98 you will need to define individual Eq instances for all your custom region types. However, you can simply define (==) = regionEquals for all those types. Hope this helps, Martijn.
participants (3)
-
Cristiano Paris
-
Jeff Heard
-
Martijn van Steenbergen