Trying to generalise (+)
to more than just Num
s, I wrote a up an Addable
class:
{-# LANGUAGE FlexibleContexts, FlexibleInstances, UndecidableInstances #-}
class Addable a where
(+) :: Addable a => a -> a -> a
instance Addable [a] where
(+) = (++)
instance Num a => Addable a where
(+) = (Prelude.+)
When trying to add (concatenate) lists, GHC complains about overlapping instances:
*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"
I know that GHC disregards context when choosing instances of typeclasses, so trying to choose between Addable [a]
and Addable a
is indeed a problem. However, I expect GHC to choose the first definition since it is more specific. Why isn't that happening?
Furthermore, is there an elegant workaround for this problem? Or am I going at this from the wrong angle?