Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid tedious implementation of Ord

I have a datatype with quite a few constructors, all of them simple enough that Haskell can derive the Ord instance automatically. As in:

data Foo a
  = A a
  | B Int
  deriving (Eq, Ord)

Now I want to add a third constructor like so:

data Foo a
  = A a
  | B Int
  | C a (a -> Bool)

But now Haskell can't manually derive Eq and Ord on Foo for me. Now, it happens that I have some domain-specific knowledge about how two values constructed with C should be ordered:

instance Eq a => Eq (Foo a) where
  -- Boilerplate I don't want to write
  A x == A y = x == y
  B x == B y = x == y
  -- This is the case I really care about
  C x f == C y g = x == y && f x == g y
  _ == _ = False

instance Ord a => Ord (Foo a) where
  -- Boilerplate I don't want to write
  A x `compare` A y = x `compare` y
  A x `compare` _ = LT

  B x `compare` B y = x `compare` y
  B x `compare` A _ = GT
  B _ `compare` _ = LT

  -- This is the case I really care about
  C x f `compare` C y g
    | x == y = f x `compare` g y
    | otherwise = x `compare` y
  C{} `compare` _ = GT

But in order to do this, I also have to manually implement the ordering on A and B values, which is really tedious (especially for the Ord instance).

Is there any trick that would allow me to implement (==) and compare only on the C case, but somehow get the "default" behaviour on the other constructors?

like image 588
Mathias Vorreiter Pedersen Avatar asked Jan 28 '18 14:01

Mathias Vorreiter Pedersen


1 Answers

You could parameterize Foo with the types of special cases, then implement special instances separately for newtypes:

data Foo' c a
  = A a
  | B Int
  | C (c a)
  deriving (Eq, Ord)

data C a = MkC a (a -> Bool)

instance Eq a => Eq (C a) where
  MkC x f == MkC y g = x == y && f x == g y

instance Ord a => Ord (C a) where
  MkC x f `compare` MkC y g
    | x == y = f x `compare` g y
    | otherwise = x `compare` y

type Foo = Foo' C
like image 57
András Kovács Avatar answered Sep 28 '22 10:09

András Kovács