让表达式中的do会导致错误

时间:2011-09-18 07:05:24

标签: haskell

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等,一切正常。

1 个答案:

答案 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