我正在使用API的奴仆库。它运行在:EitherT (Int, String) IO a monad中。我有一个带有IO Maybe a类型的函数,并且希望使用它。
下面是一个有用的例子:
sourcesGetAll :: EitherT (Int, String) IO [Source]
sourcesGetAll = liftIO $ sourcesList h
sourcesList :: IO [Source]但是现在我想把这两个函数结合起来
sourcesFind :: IO (Maybe Source)
sourcesGetOne :: EitherT (Int, String) IO Source
sourcesGetOne = ???我想这样做:
maybeNotFound :: Maybe a -> Either (Int, String) a
maybeNotFound Nothing = Left (404, "Not Found")
maybeNotFound Just a = Right a我怎么处理那些花哨的单簧管呢?
发布于 2015-04-15 17:03:06
您可以使用hoistEither :: Monad m => Either a b -> EitherT a m b来实现这一点:
maybeNotFoundT :: IO (Maybe a) -> EitherT (Int, String) IO a
maybeNotFoundT maAct = do
ma <- liftIO maAct -- get the Maybe a. Now ma :: Maybe a
hoistEither $ maybeNotFound ma发布于 2015-04-15 17:03:15
您可以将其分解为两个独立的问题:
IO (Maybe a)转换为MaybeT IO aMaybeT IO a转换为EitherT (Int, String) a第一个问题通过使用MaybeT构造函数解决:
MaybeT :: IO (Maybe a) -> MaybeT IO a第二个问题通过使用来自noteT库的errors来解决:
noteT :: Monad m => a -> MaybeT m b -> EitherT a m b发布于 2015-04-15 17:18:28
另一个答案是,由于在freenode上争吵不休:
sourcesGetOne = EitherT $ maybeNotFound <$> sourcesFind所以问题是如何写一个函数。
IO (Maybe a) -> EitherT (Int, String) IO a给出了一个函数f :: Maybe a -> Either (Int, String) a,那么一种方法是..。myFunc action = EitherT (f <$> action)如果你看一下EitherT的文档-- https://hackage.haskell.org/package/either-4.3.3.2/docs/Control-Monad-Trans-Either.html。然后你会看到EitherT (Int, String) IO a,实际上只是一个包装好的IO (Either (Int, String) a)
https://stackoverflow.com/questions/29655874
复制相似问题