I am currently working through chapter 6 and struggling with the
problem of overlapping instances (page 153).
If I type in
> toJValue [("foo","bar")]
I get the error message as mentioned in the book:
Overlapping instances for JSON [([Char], [Char])]
arising from a use of `toJValue' at <interactive>:1:0-24
Matching instances:
instance (JSON a) => JSON [a]
-- Defined at /Users/timscheffler/2009/Januar09/RWH/ch06/
BrokenClass.hs:12:9-28
instance (JSON a) => JSON [(String, a)]
-- Defined at /Users/timscheffler/2009/Januar09/RWH/ch06/
BrokenClass.hs:16:9-38
In the expression: toJValue [("foo", "bar")]
In the definition of `it': it = toJValue [("foo", "bar")]
But I don't understand this.
If I define
instance (JSON a) => JSON [a] where
<as seen on page 152>
the type a must be an instance of JSON, right?
So taking the input "toJValue [("foo","bar")]" the type ("foo", "bar")
must be an instance of JSON in order to cause ambiguity, but if I try to
> toJValue ("foo","bar")
ghci tells me, that
No instance for (JSON ([Char], [Char]))
what I expected.
So I don't understand why there is an ambiguity at all. In my
understanding the only possibility would be the instance (JSON a) =>
JSON [(String, a)].
What am I missing?
Many thanks in advance!
Tim
GHC's instance selection engine only looks at the 'head' of the
declared instances, i.e. that which is on the right hand side of the
arrow. So in the instance 'JSON a => JSON [a]', it won't consider the
'JSON a' constraint on the left.
Personally I would have liked GHC to use a full-fledged constraint
solver, and I've heard SPJ mention the possibility a few times, but as
of yet that's not how it works.
Cheers,
/Niklas