【问题标题】:Why can't I get time in a `do` block?为什么我不能在 `do` 块中获得时间?
【发布时间】:2013-01-27 09:09:48
【问题描述】:

我有这个功能,它负责网络聊天中的通信。没有t <- getClockTime 一切正常(这里有代码):

talk :: WS.Protocol p => MVar State -> Client -> WS.WebSockets p ()
talk state client@(user, sink) = flip WS.catchWsError catchDisconnect $ 
  forever $ do
    t <- getClockTime
    msg <- WS.receiveData
    case () of
      () | T.unpack(msg) == "#list" -> liftIO $ readMVar state >>= listClients client
        | T.unpack(msg) == "#time" -> liftIO (sendTime client)
        | "#name" `T.isPrefixOf` msg -> liftIO (command msg client)
        | otherwise -> liftIO $ readMVar state >>= broadcast
          (user `mappend` msg)
  where
    catchDisconnect e = case fromException e of
        Just WS.ConnectionClosed -> liftIO $ modifyMVar_ state $ \s -> do
            let new_state = removeClient client s
            return new_state
        _ -> return ()

t &lt;- getClockTime 出现错误:

Couldn't match type `WS.WebSockets p0' with `IO'
Expected type: IO Text
  Actual type: WS.WebSockets p0 Text
In a stmt of a 'do' block: msg <- WS.receiveData
In the second argument of `($)', namely
  `do { t <- getClockTime;
        msg <- WS.receiveData;
        case () of {
          ()
            | T.unpack (msg) == "#list"
            -> liftIO $ readMVar state >>= listClients client
            | T.unpack (msg) == "#time" -> liftIO (sendTime client)
            | "#name" `T.isPrefixOf` msg -> liftIO (command msg client)
            | otherwise
            -> liftIO $ readMVar state >>= broadcast (user `mappend` msg) } }'
In the second argument of `($)', namely
  `forever
   $ do { t <- getClockTime;
          msg <- WS.receiveData;
          case () of {
            ()
              | T.unpack (msg) == "#list"
              -> liftIO $ readMVar state >>= listClients client
              | T.unpack (msg) == "#time" -> liftIO (sendTime client)
              | "#name" `T.isPrefixOf` msg -> liftIO (command msg client)
              | otherwise
              -> liftIO $ readMVar state >>= broadcast (user `mappend` msg) } }'

我怎样才能得到这个时间并将它与 msg 连接起来?

【问题讨论】:

    标签: haskell time io websocket


    【解决方案1】:

    因为你的 monad 不是 IO。我不知道WS.WebSockets是什么,但如果是this one,它就是MonadIO的一个实例,所以你可以使用liftIOgetClockTime。我建议阅读更多关于此类代码的 monad 转换器的信息,因为提升会出现很多。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-08
      • 2014-08-20
      • 2012-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多