[英]Right type signature for type parameter in Haskell
我有两种数据类型,并希望编写一个返回这些数据类型数据的类:
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
如果我只有一个类型D1或D2,我可以在类型签名中命名,但在有多种可能性的情况下我该怎么办? 这甚至可能吗?
你需要让D1
和D2
的情况下, D
代替D1 a
和D2 a
。 然后你就可以量化extract
了a
,并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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.