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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With