繁体   English   中英

具体类型而不是类型类的“实例”?

[英]`instance` for concrete type instead of typeclass?

我定义了一个简单的列表类型:

data MyList a = End
               |Entry a (MyList a)

我没有deriving (Show)而是为所有MyList a实现了自己的显式实现,其中aShow的实例。

instance Show a => Show (MyList a)
  where show End = ""
        show (Entry a l) = (show a) ++","++(show l)

这工作得很好。 现在,我想更改为仅MyList StringShow的实例,为此我写了

instance Show (MyList String)
  where show End = ""
        show (Entry a l) = a ++","++(show l)

但这导致了一个错误,我不明白:

Illegal instance declaration for `Show (MyList String)'
  (All instance types must be of the form (T a1 ... an)
   where a1 ... an are *distinct type variables*,
   and each type variable appears at most once in the instance head.
   Use FlexibleInstances if you want to disable this.)
In the instance declaration for `Show (MyList String)'

谁能解释为什么这行不通以及这个错误告诉我什么?

该错误告诉您标准的Haskell不允许这种实例定义。 确切地说,

All instance types must be of the form (T a1 ... an)
where a1 ... an are *distinct type variables*,
and each type variable appears at most once in the instance head.

原因之一是,如果您保留了两个实例定义,则编译器将不知道为MyList String选择哪个,因为它们都匹配。 (您可能还想看看重叠实例规则 。)

在实例类型的形式上具有这种约束保证了类型检查将始终终止,并且尽管当然存在具有此类形式的实例的有效程序和可类型检查的程序,但这只是它的工作方式:Haskell中的某些限制是保守的。

在您的特定情况下,只需按照编译器的建议(即启用FlexibleInstances )进行操作即可,并且此扩展在终止方面是安全的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM