我有两个函数,一个尝试从Web服务获取令牌并可能失败,另一个尝试使用此令牌获取用户名并可能失败。
getToken :: IO (Maybe Token)
getUsername :: Token -> IO (Maybe String)
我想获取getToken的结果并将其提供给getUsername
。如果只有IO
或Maybe
,我可以简单地使用bind,但由于有嵌套的monad,我不能。我怎样才能写出与getToken >>= getUsername :: IO (Maybe String)
相当的东西?
更一般地说,哪个函数的类型为m1 m2 a -> (a -> m1 m2 b) -> m1 m2 b
?
奖金问题:如何在IO
上下文中使用附加说明来做到这一点?
答案 0 :(得分:10)
我已经定义了一个函数useToken
来显示你的用例:
type Token = String
getToken :: IO (Maybe Token)
getToken = undefined
getUsername :: Token -> IO (Maybe String)
getUsername = undefined
useToken :: IO (Maybe String)
useToken = do
token <- getToken
case token of
Just x -> getUsername x
Nothing -> return Nothing
如果您不想使用do
表示法,那么您可以使用:
useToken2 :: IO (Maybe String)
useToken2 = getToken >>= \token -> maybe (return Nothing) getUsername token
或者使用monad变换器,您的代码将变得更简单:
import Control.Monad.Trans.Maybe
type Token = String
getToken :: MaybeT IO Token
getToken = undefined
getUsername :: Token -> MaybeT IO String
getUsername = undefined
useToken :: MaybeT IO String
useToken = do
token <- getToken
getUsername token
请注意,您也可以直接提升monad变压器内的IO操作。正如@Robedino指出的那样,现在代码将更加简洁而不用表示法:
useToken :: MaybeT IO String
useToken = getToken >>= getUsername
答案 1 :(得分:3)
正如评论中的人所说,你应该只使用monad变形金刚。
但是你可以在你的情况下避免这种情况。 Monads一般不会通勤,因此您无法使用此签名编写函数
bind' :: (Monad m, Monad n) => m (n a) -> (a -> m (n b)) -> m (n b)
但是一切正常,如果内部monad是Traversable
类的实例:
import Data.Traversable as T
import Control.Monad
joinT :: (Monad m, Traversable t, Monad t) => m (t (m (t a))) -> m (t a)
joinT = (>>= liftM join . T.sequence)
liftMM :: (Monad m, Monad n) => (a -> b) -> m (n a) -> m (n b)
liftMM = liftM . liftM
bindT :: (Monad m, Traversable t, Monad t) => m (t a) -> (a -> m (t b)) -> m (t b)
bindT x f = joinT (liftMM f x)
和Maybe
monad是;因此
type Token = String
getToken :: IO (Maybe Token)
getToken = undefined
getUsername :: Token -> IO (Maybe String)
getUsername = undefined
useToken :: IO (Maybe String)
useToken = getToken `bindT` getUsername
另外,使用{-# LANGUAGE RebindableSyntax #-}
可以写
(>>=) = bindT
useToken :: IO (Maybe String)
useToken = do
x <- getToken
getUsername x
<强>更新强>
使用类型级别撰写
newtype (f :. g) a = Nested { runNested :: f (g a) }
您可以为嵌套monad定义monad实例:
instance (Monad m, Traversable t, Monad t) => Monad (m :. t) where
return = Nested . return . return
x >>= f = Nested $ runNested x `bindT` (runNested . f)
那么你的例子就是
type Token = String
getToken :: IO (Maybe Token)
getToken = undefined
getUsername :: Token -> IO (Maybe String)
getUsername = undefined
useToken :: IO (Maybe String)
useToken = runNested $ Nested getToken >>= Nested . getUsername
或者您可以使用MaybeT
变换器:
type Nested = (:.)
type Token = String
getToken :: Nested IO Maybe Token
getToken = undefined
getUsername :: Token -> Nested IO Maybe String
getUsername = undefined
useToken :: Nested IO Maybe String
useToken = getToken >>= getUsername
runUseToken :: IO (Maybe String)
runUseToken = runNested useToken