这是一个简单的例子:
data T a b = T a b deriving (Show)
instance Functor (T a) where
fmap f (T x y) = T x (f y)
为什么我不能在实例声明中省略a
,并编写如下内容:
instance Functor (T _) where
?
a
的类型显然与该实例无关! (在我看来,它确实更具可读性)。
很明显我们可以忽略函数参数的值。为什么不允许忽略类型变量的值?
最佳答案
简而言之,类型类实例参数不遵守模式匹配规则,为此 _
被设计为按我希望的方式工作。
Haskell 明确禁止创建类型变量重复的实例:
An instance declaration introduces an instance of a class. Let class cx => C u where { cbody } be a class declaration. The general form of the corresponding instance declaration is:
instance cx′ => C (T u1 … uk) where { d }
where k ≥ 0. The type (T u1 … uk) must take the form of a type constructor T applied to simple type variables u1, … uk; furthermore, T must not be a type synonym, and the ui must all be distinct.This prohibits instance declarations such as:
instance C (a,a) where ... instance C (Int,a) where ... instance C [[a]] where ...
实例声明中“类型模式匹配”的可能性很可能更加复杂,并且可能产生不同的含义,因此我可以理解为什么没有引入 _
;。
关于haskell - 为什么在创建类型类实例时不能下划线(忽略)类型变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27945450/