4

完整代码https://github.com/gertcuykens/haskell-design

我怎样才能从 Maybe Text 类型中提升 Maybe

application :: MVar ServerState -> WS.Request -> WS.WebSockets WS.Hybi10 ()
application state rq = do
    WS.acceptRequest rq
    WS.getVersion >>= liftIO . putStrLn . ("Client version: " ++)
    sink <- WS.getSink
    msg <- WS.receiveData
    clients <- liftIO $ readMVar state
    url <- liftIO fbUrl

    let prefix = "Facebook code"
    let code = T.drop (T.length prefix) msg

    let a = ("code",T.unpack code)
    e <- liftIO $ fbEmail $ (\(x,y) -> (C.pack x, C.pack y)) a

    let client = (e, sink) --ERROR

    case msg of
        _   | not (prefix `T.isPrefixOf` msg) -> do
                WS.sendTextData ("Facebook login " `mappend` url :: Text)
            | any ($ fst client)
                [T.null, T.any isPunctuation, T.any isSpace] ->
                    WS.sendTextData ("Facbook code invalid" :: Text)
            | clientExists client clients ->
                WS.sendTextData ("User already exists" :: Text)
            | otherwise -> do
                liftIO $ modifyMVar_ state $ \s -> do
                    let s' = addClient client s
                    WS.sendSink sink $ WS.textData $
                        "Welcome! Users: " `mappend`
                        T.intercalate ", " (map fst s)
                    broadcast (fst client `mappend` " joined") s'
                    return s'
                talk state client

    Couldn't match expected type `Maybe Text' with actual type `Text'
    Expected type: Maybe Text -> Bool
      Actual type: Text -> Bool
    In the expression: T.null
    In the second argument of `any', namely
      `[T.null, T.any isPunctuation, T.any isSpace]'
4

1 回答 1

4

您的fbEmail函数返回一个Maybe Text. 如果您希望它始终是 a Just,您可以使用变量绑定左侧的模式来从中获取Text

Just email <- liftIO . fbEmail $ both C.pack a

使用以下帮助程序来提高可读性:

both :: (a -> b) -> (a, a) -> (b, b)
both f (x, y) = (f x, f y)

但是,这会忽略错误,因此您应该使用其中一种Data.Maybe功能,例如fromMaybeor maybe。或者,您也可以使用显式case表达式:

maybeEmail <- ...
case maybeEmail of
  Just email -> ...  -- Do something with "email".
  Nothing ->    ...  -- Handle missing emails.

如果您不需要根据是否fbEmail返回Nothing或在调用者中做不同的事情Just,您可以(并且应该)将此逻辑移动到fbEmail自身中。

于 2012-07-28T01:19:46.067 回答