我一直在浏览 Bryan O'Sullivan 和他的同事的“Real World Haskell”,并在 Windows 下遇到了我称之为 GHCi 版本 7.8.3 的意外“松懈”。我“:加载”以下 -
module JSONModule where
data JValue = JNumber Double
| JBool Bool
deriving ( Show, Eq, Ord )
class JSON a where
toJValue :: a -> JValue
fromJValue :: JValue -> Either String a
fromJBool (JBool b) = Right b
fromJBool _ = Left "not a JSON boolean"
instance JSON Double where
toJValue = JNumber
fromJValue = doubleToJValue id
instance JSON Bool where
toJValue = JBool
fromJValue = fromJBool
doubleToJValue :: (Double -> a) -> JValue -> Either String a
doubleToJValue f (JNumber v) = Right (f v)
doubleToJValue _ _ = Left "not a JSON number"
然后,在 ghci 中:
*JSONModule> :r
[1 of 1] Compiling JSONModule ( JSONModule.hs, interpreted )
Ok, modules loaded: JSONModule.
*JSONModule> toJValue False
JBool False
*JSONModule> fromJValue it
Left "not a JSON number"
虽然这是真的,但这不是我们所期望的。我认为 ghci 应该告诉我放风筝,因为 fromJValue 有 2 个实例。确实,如果我指定
fromJValue it :: Either String Bool
我得到正确的错误。问题似乎是 doubleToJValue。消除 JSON Double 实例,并将 JChar Char 构造函数添加到 JValue 和 JSON Char 的相应实例,我从 ghci 得到预期的“模糊”响应。所以我认为有一个错误。注释?谢谢...