Reputation: 324
How to write Haskell code like (with language extension GADTs
and MultiParamTypeClasses
):
class MyClass f a where
func :: a -> f a
data MyData a where
Cons1 :: a -> MyData a
Cons2 :: MyData a
instance MyClass MyData a where
func (Cons1 x) = -- implement func for (Cons1 x)
instance MyClass MyData Int where
func Cons2 = -- implement func for Cons2 and don't need to implement func (Cons1 x)
instance MyClass MyData String where
func Cons2 = -- implement func for Cons2 and don't need to implement func (Cons1 x)
So for different a
, we don't have to repeat func (Cons1 x)
.
Upvotes: 0
Views: 87
Reputation: 152837
This isn't really related to classes at all. As usual, to share code, you just call a function that does the shared thing.
f1 (Cons1 x) = ...
f2 Cons2 = ...
f2 other = f1 other
f3 Cons2 = ...
f3 other = f1 other
This works whether f2
and f3
are class methods or not.
Upvotes: 1