我想找出Haskell的json库。然而,我在ghci中遇到了一些问题:
Prelude> import Text.JSON
Prelude Text.JSON> decode "[1,2,3]"
<interactive>:1:0:
Ambiguous type variable `a' in the constraint:
`JSON a' arising from a use of `decode' at <interactive>:1:0-15
Probable fix: add a type signature that fixes these type variable(s)我认为这与类型签名中的a有关:
decode :: JSON a => String -> Result a有人能告诉我:
发布于 2010-12-24 01:02:50
您需要指定要返回的类型,如下所示:
decode "[1,2,3]" :: Result [Integer]
-- Ok [1,2,3]如果该行是一个更大程序的一部分,您将继续使用decode的结果,那么可以推断类型,但是由于ghci不知道您需要哪种类型,所以它无法推断它。
这也是read "[1,2,3]"在没有类型注释或更多上下文的情况下不能工作的原因。
发布于 2010-12-24 05:00:26
解码功能定义如下:
decode :: JSON a => String -> Result a在实际程序中,类型推理机通常可以从解码中找出期望的类型。例如:
userAge :: String -> Int
userAge input = case decode input of
Result a -> a
_ -> error $ "Couldn't parse " ++ input在这种情况下,userAge的类型会导致打字机推断解码的返回值,在这种情况下,是Result Int。
但是,在decode中使用GHCi时,必须指定值的类型,例如:
decode "6" :: Result Int
=> Ok 6发布于 2010-12-24 01:07:23
快速浏览文档似乎表明,此函数的目的是允许您将JSON读入任何受支持类型的Haskell数据结构,如下所示
decode "[1, 2, 3]" :: Result [Int]应起作用
https://stackoverflow.com/questions/4523598
复制相似问题