Haskell中类型参数的右类型签名

two*_*two 4 polymorphism haskell types type-signature parametric-polymorphism

我有两种数据类型,并希望编写一个返回这些数据类型数据的类:

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
Run Code Online (Sandbox Code Playgroud)

如果我只有一个类型D1或D2,我可以在类型签名中命名,但在有多种可能性的情况下我该怎么办?这甚至可能吗?

sep*_*p2k 8

你需要制作D1D2实例D而不是D1 aD2 a.然后你就可以量化extracta,使extract返回a了的D所有a.

因为那可能不是很清楚(对不起):

class D d where
    -- `d` is the type constructor that's 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
Run Code Online (Sandbox Code Playgroud)