作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是 Haskell 中的代码:
class Fooable a where
foo :: a -> a
instance Fooable (a, a) where
foo = ...
如果没有 FlexibleInstances
扩展,这样的代码将无法在传统 Haskell 中编译。错误消息会显示:
Illegal instance declaration for ‘Fooable (a, 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 ‘Fooable (a, a)’
问题是,实际上不可能使元组 (a, a)
成为任何类型类的成员,因为每个类型变量在实例头中最多出现一次
?
最佳答案
没有办法直接在实例中强制执行 (a, b)
的关系(没有 FlexibleInstances
或其他扩展),但它们可能是等价。
这意味着如果 Fooable (a, b)
是一个实例,那么如果 a
可以等于 b
,则 Fooable ( a,a)
也是一个实例。考虑获得更多实例。
但是,有一种解决方法:
newtype Tuple a = Tuple {unTuple :: (a, a)}
instance Fooable (Tuple a) where
foo = id
这不是地球上最漂亮或最好的东西,但至少在运行时它的行为就像没有包装器一样。
关于haskell - 是否可以使 (a, a) 成为 Haskell 中类型类的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32593576/
我是一名优秀的程序员,十分优秀!