'How to only implement part of the parameters of the MultiParamTypeClasses

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).



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel Wagner