【发布时间】:2014-09-10 15:01:29
【问题描述】:
美好的一天。我是 Haskell 的新手。关于声明和实例化一些自定义类,我不清楚一件事。
haskell 中有一个标准类
Integral。根据hackage,Integral声明了强制方法quot :: a -> a -> a。所以这意味着该类的每个实例都应该有这个方法实现,对吧?我们可以声明一些函数,使用 Integral 作为参数,例如:
proba :: (Integral a) => a -> a -> a
proba x y = x `quot` y
到目前为止一切顺利
- 现在让我们声明我们自己的 Proba 类:
class Proba a where
proba :: a -> a -> a
我可以像这样实现 Int 或 Integer(或其他数据类型)实例:
instance Proba Integer where
proba x y = x `quot` y
instance Proba Int where
proba x y = x `quot` y
但我不想。 我希望每个 Integral 都有一个实例。但是当我尝试这样做时,我得到一个错误:
instance (Integral a) => Proba a where
proba x y = x `quot` y
Illegal instance declaration for `Proba a'
(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 `Proba a'
好的,它似乎要求我提供不同类型的变量,而不是类。但为什么?!为什么仅仅在这里有一个Integral 还不够?因为quot 是为每个Integral 声明的,所以这个实例应该对每个Integral 都有效,不是吗?
也许有办法达到同样的效果?
【问题讨论】:
-
Use FlexibleInstances if you want to disable this.你试过吗? -
我肯定会这样做,但我想知道为什么这些东西隐藏在某些自定义选项后面并且默认情况下不可用?
-
因为原因;这在技术上是对语言默认工作方式的扩展。您可以阅读所有这些here。
标签: haskell