2016-04-30 93 views
0

我是新来的Haskell和我有JValue一个问题,我以前把它定义为:哈斯克尔 - 无法匹配,期望型“JValue”与实际型“[(字符串,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)]’ 

我在做什么错?我可能会让自己变得太复杂。谢谢

+0

除了你的问题,我会建议你使用'也许Int'结果类型,而不是使用魔法值' -1“表示”未找到“。同样''JObject(Map String JValue')会是一个更好的选择,你可以得到大量的Map函数!最后你的函数是部分的,你需要考虑'JObject'之外的'JValue',最简单的解决方案是使用'getPosition _ x _ = error $“错误:getPosition中预期的JObject,但得到:”++ show x“,它仍然是部分函数,​​但错误信息更好 – epsilonhalbe

+0

即使有效位置必须是一个正整数,最好是通过返回'Maybe Int'而不是'Int'来确定是否找到了字符串,在这种情况下,如果找不到字符串,则返回'Nothing',并且'只需x '如果它在'x'位置找到的话 – chepner

+0

Btw。除非你为了学习的目的这么做,否则使用['aeson'](https://hackage.haskell.org/package/aeson)而不是编写你自己的JSON -图书馆 – epsilonhalbe

回答

3

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

当你想找到一个列表中的索引,使用findIndexData.List

getPosition word (JObject tuples) = 
     findIndex (\(name,_) -> name == word) tuples 
相关问题