Problem with typeclass

Hi all, Below is an example from the book "Real world haskell" data JValue = JString String | JBool Bool | JNumber Int deriving(Show) class JSON a where toJValue :: a -> JValue fromJValue :: JValue -> Either String a instance JSON JValue where toJValue = id fromJValue = Right instance JSON Bool where toJValue = JBool fromJValue (JBool a) = Right a fromJValue _ = Left "Not a JValue" I'm trying to test this in ghci :
fromJValue (JBool True)
and i got <interactive>:1:0: Ambiguous type variable `a' in the constraint: `JSON a' arising from a use of `fromJValue' at <interactive>:1:0-22 Probable fix: add a type signature that fixes these type variable(s) I don't understand where i have to declare a type signature ? in the class definition for "JSON a" ? in the instance declaration for "JSON Bool" ? Thanks in advance. Sheb

Hello Sebastien Try
(fromJValue (JBool True)) :: Bool
Or
(fromJValue (JBool True)) :: JValue
The class function /fromJValue/ is polymorphic on its answer, so you need to tell GHC / GHCi what type the answer will be. GHC can't infer it because it could be more than one type. Best wishes Stephen
participants (2)
-
Sebastien Geffroy
-
Stephen Tetley