[Haskell-cafe] Typeclasses question in "Real World Haskell" book

Angel de Vicente angelv at iac.es
Mon Jul 26 09:16:36 EDT 2010


Hi,

I'm stuck at page 151 of Real World Haskell and hoping that perhaps some 
of you can give me a hand here...

The code that is giving me trouble is below.

data JValue = JString String
             | JNumber Double
             | JBool Bool
             | JNull
             | JObject [(String, JValue)]
             | JArray [JValue]
               deriving (Eq, Ord, Show)

type JSONError = String

class JSON a where
     toJValue :: a -> JValue
     fromJValue :: JValue -> Either JSONError a

instance JSON JValue where
     toJValue = id
     fromJValue = Right

instance JSON Bool where
     toJValue = JBool
     fromJValue (JBool b) = Right b
     fromJValue _ = Left "not a JSON boolean"


I don't understand how the JSON typeclass is defined, in particular the
fromJValue definition.

For instance, when defining the instance for Bool types, then I
understand that both functions (toJValue and fromJValue) will be called
upon when we supply a Bool type, but then the (JBool b) type in function 
fromJValue doesn't match....

toJValue is no problem, but I cannot understand how fromJValue is
supposed to work, and the comments in the online book
(http://book.realworldhaskell.org/read/using-typeclasses.html) don't
help with this either.

  *Main> :load ch6
[1 of 1] Compiling Main             ( ch6.hs, interpreted )
Ok, modules loaded: Main.
*Main> toJValue False
JBool False
*Main> :type it
it :: JValue
*Main> fromJValue False

<interactive>:1:11:
     Couldn't match expected type `JValue' against inferred type `Bool'
     In the first argument of `fromJValue', namely `False'
     In the expression: fromJValue False
     In the definition of `it': it = fromJValue False
*Main> fromJValue (JBool False)

<interactive>:1:0:
     Ambiguous type variable `a' in the constraint:
       `JSON a' arising from a use of `fromJValue' at <interactive>:1:0-23
     Probable fix: add a type signature that fixes these type variable(s)
*Main>



Any pointers?

Thanks a lot,
Ángel de Vicente
-- 
http://www.iac.es/galeria/angelv/

High Performance Computing Support PostDoc
Instituto de Astrofísica de Canarias
---------------------------------------------------------------------------------------------
ADVERTENCIA: Sobre la privacidad y cumplimiento de la Ley de Protección de Datos, acceda a http://www.iac.es/disclaimer.php
WARNING: For more information on privacy and fulfilment of the Law concerning the Protection of Data, consult http://www.iac.es/disclaimer.php?lang=en



More information about the Haskell-Cafe mailing list