次のコードがあります。
import Text.JSON
-- get the value in a JSON object that has this key
getByKey :: JSValue -> String -> Maybe JSValue
getByKey object key =
case object of
JSObject a ->
getFirst keyValues keyMatches
where keyValues = fromJSObject object
keyMatches (key', value) = key == key'
_ -> Nothing
-- get the first item in the list matching a predicate
getFirst :: [a] -> (a -> Bool) -> Maybe a
getFirst [] pred = Nothing
getFirst (x:xs) pred =
case pred x of
True -> Just x
False -> getFirst xs pred
これを使用して、任意の JSValue の値にアクセスしたいと考えています。ただし、コンパイルされません。
Prelude> :load Example
[1 of 1] Compiling Main ( Example.hs, interpreted )
Example.hs:8:26:
Couldn't match expected type `JSValue'
with actual type `(String, t0)'
Expected type: JSValue -> Bool
Actual type: (String, t0) -> Bool
In the second argument of `getFirst', namely `keyMatches'
In the expression: getFirst keyValues keyMatches
Example.hs:9:38:
Couldn't match expected type `JSObject e0'
with actual type `JSValue'
In the first argument of `fromJSObject', namely `object'
In the expression: fromJSObject object
In an equation for `keyValues': keyValues = fromJSObject object
Failed, modules loaded: none.
私は何を間違えましたか?
編集fromJSObject object
: Daniel Fischer は親切にもそうあるべきだと指摘しましたfromJSObject a
。ただし、これは型チェッカーを満足させるには十分ではありません。
[1 of 1] Compiling Main ( Example.hs, interpreted )
Example.hs:8:16:
Couldn't match expected type `JSValue'
with actual type `(String, JSValue)'
Expected type: [JSValue]
Actual type: [(String, JSValue)]
In the first argument of `getFirst', namely `keyValues'
In the expression: getFirst keyValues keyMatches
Failed, modules loaded: none.