Some clarity please!

Michael Karcher usenet at mkarcher.dialup.fu-berlin.de
Tue Apr 22 13:28:27 EDT 2008


In gmane.comp.lang.haskell.prime Aaron Denney <wnoise at ofb.net> wrote:
> > Prelude> :i Ord
> > class (Eq a) => Ord a where
> >   compare :: a -> a -> Ordering
> >   (<) :: a -> a -> Bool
> >   (>=) :: a -> a -> Bool
> >   (>) :: a -> a -> Bool
> >   (<=) :: a -> a -> Bool
> >   max :: a -> a -> a
> >   min :: a -> a -> a
> >
> > ..while all functions could be easily derived from 'compare'.  Or from
> > the Eq instance's (==) and (<), say.
> >
> > What is the reason for this?  Efficiency?  (Which couldn't be handled
> > equally well by RULES?)  Otherwise, it looks like an invitation for
> > writing inconsistent instances.
> 
> My impression (which may not be entirely accurate) is not primarily for
> efficiency (though that is one reason), but for ease of implementation.
[...]
> max and min seem to have neither justification going for them, although
> I suppose it's technically possible to write compare in terms of them
> and (==).

I am quite late to join this thread, but as I just read the thread
about Conal's AddBounds where he had a very valid point for
implementing min/max without resorting to <= or compare:

min [] ys = []
min xs [] = []
min (x:xs) (y:ys)
 | cmp == LT = (x:xs)
 | cmp == GT = (y:ys)
 | cmp == EQ = x:min xs ys
    where cmp = compare x y

This is a properly lazy implementation for min (the one in GHC's
prelude is not), as it is able to calculate (take 5 $ min [1,2..]
[1,2..]). This is not possible if min has to wait for compare or <= to
compare the full lists before returning the head.

Regards,
  Michael Karcher



More information about the Haskell-prime mailing list