当我在 Haskell 中输入以下内容时:
{-# LANGUAGE FlexibleInstances, OverlappingInstances, UndecidableInstances #-}
class Class a
instance Class a
instance Eq a => Class a
当我将其加载到 GHCi 中时,出现此错误:
Test.hs:5:10:
Duplicate instance declarations:
instance [overlap ok] Class a -- Defined at Test.hs:5:10
instance [overlap ok] Eq a => Class a -- Defined at Test.hs:6:10
Failed, modules loaded: none.
我有点理解为什么它失败了,因为两者都是 a
的实例,而且都不是更具体的,假设忽略了约束。但为什么说重叠可以呢?
此外,是否可以添加语言扩展来允许这些类型的重叠工作,这会有用吗?
最后,我希望在当前的 GHC 中以另一种方式实现(我的目的是使用一段代码作为 Eq
的实例,另一段代码用于其余部分)?
最佳答案
"But why is it saying that overlap is ok?"
因为你用语言杂注这么说了。
请注意,就 GHC 的实例解析而言,这些实例不仅是重叠的,而且是相同的。 GHC 根本不知道如何区分这些实例,因此它拒绝它们。甚至 IncoherentInstances
也无法帮助 GHC。它将在 GHC 7.8 中有所帮助,如 Joachim Breitner just notified我。
And finally, is what I intend possible in the current GHC in another way (what I intend is to use one piece of code for instances of
Eq
and another for the rest)?
如果新的 costtraint 类型扩展使其成为可能,我不会感到惊讶,但我从未使用过它们,所以我不知道它们是如何工作的以及它们可以做什么。但如果你的代码确实有效的话,它看起来不会那么简单。
关于haskell - 重叠实例可以,但仍然失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18615649/