[Haskell] Instance declaration of classes with method type constraints
Johan Holmquist
johho590 at student.liu.se
Thu Jun 30 08:07:17 EDT 2005
> This type declaration for 'm' probably doesn't mean what you think it
> does. I think what you want is "m takes an item of type 'a' and returns
> an item of a particular type in the Num class, but I'm not going to tell
> you which one", but what this declaration really means "m takes an item
> of type 'a' and will return an item of any type you wish, so long as it
> is in the Num class".
>
> In this context 'a' and 'b' are very different kinds of type variables:
> 'a' is fixed, but 'b' is universally quantified.
Thank you Mr. Dockins for pointing that out, now I understand (I think) why my
attempts failed.
> [ ... ]
> {-# OPTIONS -fglasgow-exts #-}
> class Num b => Rect a b | a -> b where
> width :: a -> b
> height :: a -> b
>
> instance Rect IRect Int where
> width ( IRect (x1, _ ) (x2, _ ) ) = abs(x2 - x1)
> height ( IRect ( _, y1) ( _, y2) ) = abs(y2 - y1)
This works perfectly!
Anyone:
However, I haven't been able to make PRect an instance of this class (with
extensions). I might not have grasped this yet, but I came to think; if the
old class declaration would say that "width" and "height" returns something
with unfixed type in the "Num" class, then wouldn't it be possible to make
PRect an instance of that class (since PRect has a type parameter)?
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)
instance Rect PRect a where ...
This (as well as my other attemps) fail with a "Kind error: `PRect' is not
applied to enough type arguments" - error. Is there a way to do it, or am I
lost here?
regards
/johan
More information about the Haskell
mailing list