为什么我在创建类型 class 实例时不能下划线(忽略)类型变量?
Why can't I underscore (ignore) type variables when creating a type class instance?
这是一个简单的例子:
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
的类型显然与该实例无关! (在我看来,确实 更具可读性)。
很明显我们可以忽略函数参数的值。为什么不允许忽略类型变量的值?
简而言之,类型 class 实例参数不遵守模式匹配规则,因此 _
旨在按我希望的方式工作。
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 ...
在实例声明中“type-pattern-match”的可能性很可能更复杂并且可能有不同的含义,所以我明白了为什么 _
没有被引入;.
这是一个简单的例子:
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
的类型显然与该实例无关! (在我看来,确实 更具可读性)。
很明显我们可以忽略函数参数的值。为什么不允许忽略类型变量的值?
简而言之,类型 class 实例参数不遵守模式匹配规则,因此 _
旨在按我希望的方式工作。
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 ...
在实例声明中“type-pattern-match”的可能性很可能更复杂并且可能有不同的含义,所以我明白了为什么 _
没有被引入;.