使用存在类型Haskell时出现类型错误
我正在Haskell做一个存在主义类型的实验。我正在构建一个非常短的Json库,并试图构建一个折叠。 我在使用使用存在类型Haskell时出现类型错误,haskell,Haskell,我正在Haskell做一个存在主义类型的实验。我正在构建一个非常短的Json库,并试图构建一个折叠。 我在使用for all量词的代码中出错 class(Show m)=>JsonValue m 实例JsonValue Int 实例JsonValue Double 实例JsonValue字符串 实例JsonValue Bool 数据Json=JObject[(字符串,Json)] |JArray[Json] |对于所有a。(JsonValue a)=>JValue a foldJ::([(字符串
for all
量词的代码中出错
class(Show m)=>JsonValue m
实例JsonValue Int
实例JsonValue Double
实例JsonValue字符串
实例JsonValue Bool
数据Json=JObject[(字符串,Json)]
|JArray[Json]
|对于所有a。(JsonValue a)=>JValue a
foldJ::([(字符串,b)]->b)->([b]->b)->对于所有a。(JsonValue a)=>(a->b)->Json->b
foldJ对象数组值(JObject xs)=对象$map(bimap id(foldJ对象数组值))xs
foldJ对象数组值(JArray xs)=数组$map(foldJ对象数组值)xs
foldJ对象数组值(JValue x)=值x--此处出错
我使用的是-XExistentialTypes-XFlexibleInstances-XRank2Types
错误如下所示:
Json.hs:335:47: error:
• Couldn't match expected type ‘a’ with actual type ‘a1’
‘a1’ is a rigid type variable bound by
a pattern with constructor:
JValue :: forall a. JsonValue a => a -> Json,
in an equation for ‘foldJ’
at Json.hs:335:27-34
‘a’ is a rigid type variable bound by
the type signature for:
foldJ :: ([(String, b)] -> b)
-> ([b] -> b) -> forall a. JsonValue a => (a -> b) -> Json -> b
at Json.hs:(333,1)-(335,47)
• In the first argument of ‘value’, namely ‘x’
In the expression: value x
In an equation for ‘foldJ’:
foldJ object array value (JValue x) = value x
• Relevant bindings include
x :: a1 (bound at Json.hs:335:34)
value :: a -> b (bound at Json.hs:335:20)
|
335 | foldJ object array value (JValue x) = value x
| ^
Failed, one module loaded.
这真让我困惑。我使用了键入的孔,所有的东西看起来都是正确的类型,但是当我把它放在一起时,没有任何东西像往常一样起作用,签名被正确地解析,也就是说,它是关联的
foldJ :: ([(String, b)] -> b)
-> ( ([b] -> b)
-> ( ∀ a . (JsonValue a)
=> (a -> b) -> (Json -> b)
)
)
并不是说∀ 量化第二次应用程序的结果。因此,它处于协变位置,这意味着使用函数的人可以选择a
是什么类型。事实上,你的签名等同于
foldJ :: JsonValue a
=> ([(String, b)] -> b) -> ([b] -> b) -> (a -> b) -> (Json -> b)
但这不是您想要表达的:调用方无法选择类型,因为它隐藏在json结构中
实际上,您希望quantor只在a->b
参数上运行,即调用者必须提供一个适用于任何类型a
的参数
foldJ :: ([(String, b)] -> b)
-> ( ([b] -> b)
-> ( (∀ a . (JsonValue a) => (a -> b))
-> (Json -> b)
)
)