haskell - 为什么在创建类型类实例时不能下划线(忽略)类型变量?

标签 haskell instance typeclass

这是一个简单的例子:

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/

相关文章:

c++ - 从两个接口(interface)实现创建实例

haskell - 在 newtype 中实现 >>=

haskell - 定义部分应用的类型类

scala - 使用类型类建模生产者-消费者语义?

haskell - 用无点样式写 f?

haskell - 从 Haskell 的核心中删除带有重复分支的 "case"

haskell - 这个仿函数式标签的类型类的名称是什么?

java - 无法创建构造函数

java - 创建一个类实例并使用局部变量命名它(android)

list - 嵌套列表中的 Haskell `elem`