开发者

let expression in do causes error

开发者 https://www.devze.com 2023-04-05 20:43 出处:网络
import Text.JSON import Control.Monad data Status = Status { user :: St开发者_如何学Cring, text :: String } deriving Show
import Text.JSON
import Control.Monad

data Status = Status { user :: St开发者_如何学Cring, 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.

Remove let (!) = flip valFromObj in and replace tweet ! "user" with valFromObj "user" tweet etc., everything is fine.


This is caused by the monomorphism restriction, which causes the type of (!) to be inferred as JSObject JSValue -> String -> Result (JSObject JSValue) because of its usage in

userObject <- tweet ! "user"

Adding a type signature fixes the problem.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消