Proper type signature for a type parameter in Haskell

I have two data types and you want to write a class that returns data from these data types:

data D1 a = Da1 a | Db1 a 
data D2 a = Da2 a | Db2 a 

class D a where
    extract :: ??? a -> a

instance D (D1 a) where
    extract (Da1 a) = a
    extract (Db1 a) = a

instance D (D2 a) where
    extract (Da2 a) = a
    extract (Db2 a) = a

If I had only one type of D1 or D2, I could name it in a type signature, but what should I do if there are several possibilities? Is it possible?

+4
source share
1 answer

You need to do D1and D2copies Dinstead of D1 aand D2 a. Then you can quantify extractover aand make a extractreturn afrom Dfor all a.

Since this was probably not very clear (sorry):

class D d where
    -- `d` is the type constructor that an instance of `D` (i.e. `D1` or
    -- `D2`) and `a` is a new type variable that can be any possible type
    extract :: d a -> a

instance D D1 where
    extract (Da1 a) = a
    extract (Db1 a) = a
+8
source

Source: https://habr.com/ru/post/1689534/


All Articles