Show, Eq not necessary for Num
Sat, 10 Feb 2001 21:00:38 -0500
On Sun, Feb 11, 2001 at 01:37:28PM +1300, Brian Boutel wrote:
> Let me restate my question more carefully:
> Can you demonstrate a revised hierarchy without Eq? What would happen to
> Ord and the numeric classes with default class method definitions that
> use (==) either explicitly or in pattern matching against numeric
> literals? Both Integral and RealFrac do this to compare or test the
> value of signum.
I've been working on writing up my preferred hierarchy, but the short
answer is that classes that are currently derived from Ord often do
require Eq as superclasses.
In the specific cases: I think possibly divMod and quotRem should be
split into separate classes. It seems to me that divMod is the
more fundamental pair: it satisfies the identity
mod (a+b) b === mod a b
div (a+b) b === 1 + div a b
in addition to
(div a b)*b + mod a b === a.
This identity is not enough to specify divMod competely; another
reasonable choice for Integers would be to round to the nearest
integer. But this is enough to make it useful for many applications.
quotRem is also useful (although it only satisfies the second of
these), and does require the ordering (and ==) to define sensibly, so
I would make it a method of a subclass of Ord (and hence Eq). So I
would tend to put these into two separate classes:
class (Ord a, Num a) => Real a
class (Num a) => Integral a where
div, mod :: a -> a -> a
divMod :: a -> a -> (a,a)
class (Integral a, Real a) => RealIntegral a where
quot, rem :: a -> a -> a
quotRem :: a -> a -> (a,a)
I haven't thought about the operations in RealFrac and their semantics
enough to say much sensible, but probably they will again require Ord
as a superclass.
In general, I think a good approach is to think carefully about the
semantics of a class and its operations, and to declare exactly the
superclasses that are necessary to define the semantics.
Note that sometimes there are no additional operations. For instance,
declaring a class to be an instance of Real a should mean that the
ordering (from Ord) and the numeric structure (from Num) are
Note also that we cannot require Eq to state laws (the '===' above);
consider the laws required for the Monad class to convince yourself.