[Haskell] Instance declaration of classes with method type constraints

Johan Holmquist johho590 at student.liu.se
Wed Jun 29 17:53:10 EDT 2005


How do you instantiate from classes with method type constraints, such as this 

class C a where
   m :: (Num b) => a -> b


I have been trying for some time now but everything I have tried fails.

In particular, what I want to do is something like this:

class Rect a where
	width  :: (Num b) => a -> b
	height :: (Num b) => a -> b

data Num a => PRect a = PRect (a, a) (a, a) deriving (Eq, Show)
data IRect = IRect (Int, Int) (Int, Int) deriving (Eq, Show)

instance Rect IRect where
	width  ( IRect (x1, _ ) (x2, _ ) ) = abs(x2 - x1)
	height ( IRect ( _, y1) ( _, y2) ) = abs(y2 - y1)

In this case, efforts to intantiate IRect from Rect fails with error messages 
like: (using GHCI)
    Cannot unify the type-signature variable `b' with the type `Int'
        Expected type: b
        Inferred type: Int
    In the expression: x2 - x1
    In the first argument of `abs', namely `(x2 - x1)'

Again, what should I do to make this work?
Also, how is the PRect type to be instantiated?


More information about the Haskell mailing list