我正在Haskell中使用“存在类型”进行实验。我正在构建一个非常短的Json库,并试图构建一个折叠。
使用forall
量词的代码中出现错误!
class (Show m) => JsonValue m
instance JsonValue Int
instance JsonValue Double
instance JsonValue String
instance JsonValue Bool
data Json = JObject [(String, Json)]
| JArray [Json]
| forall a . (JsonValue a) => JValue a
foldJ :: ([(String, b)] -> b) -> ([b] -> b) -> forall a . (JsonValue a) => (a -> b) -> Json -> b
foldJ object array value (JObject xs) = object $ map (bimap id (foldJ object array value)) xs
foldJ object array value (JArray xs) = array $ map (foldJ object array value) xs
foldJ object array value (JValue x) = value x -- ERROR HERE
我正在使用-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.
这真让我感到困惑。香港专业教育学院使用类型的孔和一切似乎像它是正确的类型,但当我把它放在一起没有任何作用
答案 0 :(得分:3)
和往常一样,签名被解析为右关联的,即它是
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)
)
)