haskell无法匹配预期类型`Maybe Text'与实际类型`Text'

时间:2012-07-28 01:00:54

标签: haskell

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

如何从Maybe Text type

中解除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]'

1 个答案:

答案 0 :(得分:4)

您的fbEmail函数返回Maybe Text。如果您希望它始终为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.MaybefromMaybe之类的maybe函数之一。或者,您也可以使用明确的case表达式:

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

如果根据fbEmail是否返回NothingJust而不需要在调用者中执行不同的操作,则可以(并且应该)将此逻辑移动到{{ 1}}本身。