Reading the book Real world Haskell
geting below example of Overlapping instances
instance (JSON a) => JSON [a] where
toJValue = undefi
By my understanding this won't be a overlapping, as
[a]
shouldn't be a choice, since The restriction onJSON [a]
was thata
must be an instance itself ofJSON
. There is no instance ofJSON
for(String, a)
.
That's a misunderstanding. GHC does the instance selection taking only the instance head into account, and not any constraints on the instances.
instance (JSON a) => JSON [a] where
means for the purpose of instance selection the same as
instance JSON [a] where
also the context of
instance (JSON a) => JSON [(String, a)] where
is ignored for instance selection.
Thus GHC sees the two instances
instance JSON [a]
instance JSON [(String, a)]
and they both match the required
instance JSON [(String, String)]
that means you have overlap (regardless of what instances actually exist and what constraints each of the two instances has).
If an instance is selected, then the constraints are taken into account, and if they are not met, that is a type error.
These exist
ghci> :i ToJSON
...
instance ToJSON [Char]
...
instance (ToJSON a, ToJSON b) => ToJSON (a, b)
So there'd be an overlap even if GHC took context into account (see Daniel Fischer's answer).