我正在 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.
这真的让我很困惑。我使用过键入的孔,所有东西似乎都像是正确的类型,但当我把它们放在一起时没有任何效果
最佳答案
一如既往,签名被解析为右关联,即它是
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 结构中!
您真正想要的是让量化器仅在 a -> b
参数上运行,即调用者必须提供一个适用于的参数任何类型 a
。
foldJ :: ([(String, b)] -> b)
-> ( ([b] -> b)
-> ( (∀ a . (JsonValue a) => (a -> b))
-> (Json -> b)
)
)
关于haskell - 使用存在类型 Haskell 时出现类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58060824/