Re: default class methods in sub-classes
Hello,
Apparently I can't do this (in ghc or hugs -- haven't tried others):
class Space a where distance :: a -> a -> Int subtract :: a -> a -> a
class (Space a) => NormSpace a where norm :: a -> Int distance a b = norm (subtract a b)
That is, I can't make (or redefine) a default for the superclass method 'distance' in a subclass. I agree that the Haskell'98 definition doesn't claim that this should be allowed, but it seems like something that would be useful. Are there reasons not to allow this (or that I shouldn't want to do this at all)?
Apologies if this is well-covered. I couldn't find any mention of it.
the problem is, that to make something instance of NormSpace, you must first have it as instance of Space, i.e. with distance already defined. Then for this to work, the default definition in NormSpace would have to override what user defined, which looks strange. Your problem can be solved in ghc by this (but unfortunately only with -fallow-overlapping-instances -fallow-undecidable-instances (or some simmilar flags)): class HavingSubtract a where -- not sure why generic space should have subtract, subtract :: a -> a -> a -- but why not class (HavingSubtract a) => Space a where distance :: a -> a -> Int class (HavingSubtract a) => NormSpace a where norm :: a -> Int instance (NormSpace a) => Space a where distance a b = norm (subtract a b) (and there is several more examples in that I would find something like this very useful, but AFAIK there is no clean and elegant way how to do it -- you may do something simmilar using newtypes, but that is totally clumsy). Zdenek _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail
participants (1)
-
Zdenek Dvorak