[Haskell-cafe] Ord type on lists
Lemmih
lemmih at gmail.com
Sat Apr 2 18:12:45 EST 2005
On Apr 3, 2005 12:41 AM, Lloyd Smith <lloyd.g.smith at gmail.com> wrote:
> Hi everyone, I defined my own list datatype and then tried to declare
> it as an instance of type class Ord. However when I test it with
>
> Nil > Cons 1(Nil)
> I get an "ERROR - Control stack overflow"
>
> I am under the impression that the ord class defines default
> implementations of (<=), (>),(>=) so that I only have to supply the
> implementation of (<) shown below. Can some one tell me why this does
> not work the way I expect it to?
>
> My very own list data type
>
> > data List a = Nil
> > | Cons a (List a)
> > deriving (Show)
>
> Derive the equality type for list.
>
> > instance (Eq a) => Eq (List a) where
> > Nil == Nil = True
> > Nil == Cons y ys = False
> > Cons x xs == Nil = False
> > Cons x xs == Cons y ys = (x == y) && (xs == ys)
>
> Derive the ordered type for list
>
> > instance (Ord a) => Ord (List a) where
> > Nil < Nil = False
> > Nil < Cons y ys = True
> > Cons x xs < Nil = False
> > Cons x xs < Cons y ys = (x < y) && (xs < ys)
(<=), (>) and (>=) are defined using 'compare', not (<). Write
'compare' yourself and everything will be good.
But why don't you just derive Eq and Ord for List?
--
Friendly,
Lemmih
More information about the Haskell-Cafe
mailing list