import Text.JSON
import Control.Monad
data Status = Status { user :: String, text :: String } deriving Show
makeStatus :: JSObject JSValue -> Result Status
makeStatus tweet = let (!) = flip valFromObj in do
userObject <- tweet ! "user"
user <- userObject ! "screen_name"
text <- tweet ! "text"
return Status {user = user, text = text}
[1 of 1] Compiling Main ( twitter.hs, interpreted )
twitter.hs:11:27:
Couldn't match expected type `[Char]'
with actual type `JSObject JSValue'
Expected type: String
Actual type: JSObject JSValue
In the `user' field of a record
In the first argument of `return', namely
`Status {user = user, text = text}'
Failed, modules loaded: none.
删除let (!) = flip valFromObj in
并将tweet ! "user"
替换为valFromObj "user" tweet
等,一切正常。
答案 0 :(得分:8)
这是由the monomorphism restriction引起的,这会导致(!)
的类型被推断为JSObject JSValue -> String -> Result (JSObject JSValue)
,因为它在
userObject <- tweet ! "user"
添加类型签名可以解决问题。
makeStatus :: JSObject JSValue -> Result Status
makeStatus tweet = do
userObject <- tweet ! "user"
user <- userObject ! "screen_name"
text <- tweet ! "text"
return Status {user = user, text = text}
where
(!) :: JSON a => JSObject JSValue -> String -> Result a
(!) = flip valFromObj