试图推广(+)
到不仅仅是Num
s,我写了一个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 选择第一个定义,因为它更具体。为什么没有发生这种情况?
此外,这个问题是否有一个优雅的解决方法?还是我从错误的角度来看这个?