3

试图推广(+)到不仅仅是Nums,我写了一个Addable类:

{-# LANGUAGE FlexibleContexts, FlexibleInstances, UndecidableInstances #-}

class Addable a where
  (+) :: Addable a => a -> a -> a

instance Addable [a] where
  (+) = (++)

instance Num a => Addable a where
  (+) = (Prelude.+)

当尝试添加(连接)列表时,GHC 抱怨重叠实例:

*Test> "abc" + "defghi"

<interactive>:84:7:
    Overlapping instances for Addable [Char] arising from a use of `+'
    Matching instances:
      instance Num a => Addable a -- Defined at Utils.hs:23:10
      instance Addable [a] -- Defined at Utils.hs:20:10
    In the expression: "abc" + "defghi"
    In an equation for `it': it = "abc" + "defghi"

我知道 GHC 在选择类型类的实例时会忽略上下文,因此尝试在Addable [a] 和之间进行选择Addable a确实是一个问题。但是,我希望 GHC 选择第一个定义,因为它更具体。为什么没有发生这种情况?

此外,这个问题是否有一个优雅的解决方法?还是我从错误的角度来看这个?

4

1 回答 1

6

您需要启用重叠实例才能实际使用它们。OverlappingInstances在旧版本的编译器中,您可以使用扩展名对每个模块执行此操作:

{-# LANGUAGE OverlappingInstances #-}

这适用于此代码:

λ> :set -XOverlappingInstances
λ> "abc" + "def"
"abcdef"

但是,这种方法在较新版本的 GHC 中已被弃用(至少在 8.0 中):

Misc.hs:1:73-92: warning: …
    -XOverlappingInstances is deprecated: 
      instead use per-instance pragmas OVERLAPPING/OVERLAPPABLE/OVERLAPS

所以更现代的方法是在每个实例的基础上指定它:

instance {-# OVERLAPPABLE #-} Num a => Addable a where
  (+) = (Prelude.+)

这种风格的 pragma 也存在于OVERLAPPING,OVERLAPSINCOHERENT中,让您可以使用这些属性注释特定实例。

于 2016-08-29T21:41:15.667 回答