我的代码中有一个非常令人困惑的错误.我正在使用Data.Aeson包.我不认为这是包的错误.
class ToArrayFormat a where
getObjects :: (ToJSON b) => a -> b
toArrayFormat :: a -> Value
toArrayFormat a = toJSON $ getObjects a
Run Code Online (Sandbox Code Playgroud)
这段代码将无法使用错误消息进行编译:
Could not deduce (ToJSON s0) arising from a use of ‘toJSON’
from the context (ToArrayFormat a)
bound by the class declaration for ‘ToArrayFormat’
at <interactive>:(103,1)-(108,43)
The type variable ‘s0’ is ambiguous
In the expression: toJSON
In the expression: toJSON $ getObjects a
In an equation for ‘toArrayFormat’:
toArrayFormat a = toJSON $ getObjects a
Run Code Online (Sandbox Code Playgroud)
我现在很困惑.getObjects返回一个ToJSON b可以被toJSONin 消耗的实例toArrayFormat.你不能b从我的getObjects定义推断出实例吗?为什么说它ToJSON s0含糊不清?
关键是这部分:
The type variable ‘s0’ is ambiguous
Run Code Online (Sandbox Code Playgroud)
注意toJSON有类型:
toJSON :: ToJSON b => b -> Value
Run Code Online (Sandbox Code Playgroud)
另外,这个声明:
getObjects :: (ToJSON b) => a -> b
Run Code Online (Sandbox Code Playgroud)
说,getObjects可以转换a成任何类型b这是在ToJSON类.例如,如果blah是类型的值a,您可以合法地要求:
getObjects blah :: Int
getObjects blah :: String
getObjects blah :: Char
Run Code Online (Sandbox Code Playgroud)
并转换blah为Int,String或Char,因为所有这些都在ToJSON类中.这可能不是你想到的,也不是你的getObjects功能.
要理解错误消息,问题是在表达式中toJSON $ getObjects a,GHC不知道如何键入getObjects b- ToJSON类的哪个成员- Int?,String?,Char ?,其他类型?
你可以指定一个这样的具体类型:
toArrayFormat a = toJSON $ (getObjects a :: Char)
Run Code Online (Sandbox Code Playgroud)
但是,就像我说的那样,这可能不是你想到的.
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |