【问题标题】:Haskell - Couldn't match expected type ‘JValue’ with actual type ‘[(String,JValue)]’Haskell - 无法将预期类型“JValue”与实际类型“[(String,JValue)]”匹配
【发布时间】:2016-05-01 03:44:35
【问题描述】:

我是 Haskell 的新手,我对 JValue 有疑问,我之前将其定义为:

data JValue = 
    JString String
    | JNumber Double
    | JBool Bool
    | JNull 
    | JObject [(String, JValue)]
    | JArray [JValue]

我正在尝试制作一个函数

getPosition :: String -> JValue -> Int -> Int
getPosition _ (JObject []) _ = -1
getPosition word (JObject [(name,_)]) index
    | stringsAreEqual word name = index
    | otherwise = -1
getPosition word (x:xs) index = getPosition word xs (index+1)

用于在JObject 中查找元组的索引,该索引与参数中的字符串具有相同的字符串。我收到此错误:

Couldn't match expected type ‘with actual type ‘[(String, JValue)]’

我做错了什么?我可能让自己太复杂了。谢谢

【问题讨论】:

  • 除了您的问题,我建议您使用Maybe Int 作为结果类型,而不是使用魔术值-1 表示“未找到”。此外,JObject (Map String JValue 将是一个更好的选择,您可以获得一大堆 Map 功能!最后你的功能是部分的,你需要考虑JValues而不是JObject,最简单的解决方案是使用getPosition _ x _ = error $ "Error: expected JObject in getPosition but got: " ++ show x,它仍然是一个部分功能,但错误信息更好。
  • 即使有效位置必须是正整数,最好通过返回Maybe Int 而不是Int 来明确您是否找到该字符串,在这种情况下您会返回Nothing 如果找不到字符串,Just x 如果在位置 x 找到。
  • 顺便说一句。除非您出于学习目的这样做,否则请使用 aeson 而不是编写自己的 JSON 库

标签: json haskell


【解决方案1】:

在最后一个子句的第二个参数中,您对列表 (x:xs) 进行模式匹配,但必须有 JValue

如果要在列表中查找索引,请使用 findIndex from Data.List

getPosition word (JObject tuples) =
       findIndex (\(name,_) -> name == word) tuples

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-02
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    相关资源
    最近更新 更多