2

这是一些示例代码

foo :: a -> Identity (Maybe a)
foo a = do
  maybeStuff <- getStuffSometimes a
  return $ case maybeStuff of                  -- this "case" stuff is the kind
    Just stuff -> Just $ getStuffAlways stuff  -- of code I'd expect the Maybe
    Nothing -> Nothing                         -- monad to help with

getStuffSometimes :: a -> Identity (Maybe a)
getStuffSometimes a = return $ Just a

getStuffAlways :: a -> Identity a
getStuffAlways = return

-- ERROR (on the return statement of the do block)
-- Expected type: Identity (Maybe a)
--   Actual type: Identity (Maybe (Identity a))

可能有点不清楚我要做什么,所以这里有一个更详细的描述:

  • 所有有趣的东西都包装在一个计算上下文/容器中——在这种情况下,Identity为了演示。在我的实际代码中,我当然还有另一个单子。

  • foo并且getStuffSometimes应该接受某种类型的东西a并返回一个Maybe a包装在上下文中的东西——也就是说,它们要么返回Identity (Just a)(计算成功,要么Identity Nothing(计算失败)。

  • getStuffAlways是一个永远不会失败的计算——它总是返回Identity a

  • 我想foo

    1. 运行失败的计算
    2. 如果可失败计算失败,则失败(无)
    3. 如果失败的计算成功,将它与 getStuffAlways 绑定,并返回 Just (result of getStuffAlways to the result of #1)

这是 Monad Transformers 的用例情况吗?在我的情况下,我的实际 monad 有点复杂,是我的库在 IO 之上提供的多个转换器堆栈,我不完全确定如何使它适用于这种情况(我会在另一个问题中问它结果是我必须使用变压器)


跟进:

在现实生活中,我有更多类似的东西:

foo :: a -> Identity (a, Maybe a)
foo a = do
  firstPart <- getStuffAlways a

  maybeStuff <- getStuffSometimes a
  secondPart <- case maybeStuff of
    Just stuff -> Just $ getStuffAlways stuff
    Nothing -> Nothing

  return (firstPart, secondPart)

在这种情况下,构建堆栈的最佳方法是什么?

4

1 回答 1

5

是的,这是 monad 转换器的一个用例。给定一个类型的计算:

computation :: (Monad m) => m (Maybe a)

...您可以MaybeT使用MaybeT同名的构造函数将其包装起来:

MaybeT :: (Monad m) => m (Maybe a) -> MaybeT m a

MaybeT computation :: (Monad m) => MaybeT m a

然后你可以写:

foo :: MaybeT Identity a
foo = do
   stuff <- MaybeT getStuffSometimes
   lift $ getStuffAlways stuff

...并将为您MaybeT处理所有Nothing检查,确保将它们穿过您的其他 monad。

完成后,只需使用runMaybeT解包结果,在返回 a 的基本 monad 中返回一个动作Maybe

runMaybeT :: (Monad m) => MaybeT m a -> m (Maybe a)

例如:

runMaybeT foo :: Identity (Maybe a)

编辑:要回答您的后续问题,您只需执行以下操作:

foo a = do
    firstPart <- getStuffAlways
    secondPart <- runMaybeT $ do
        stuff <- MaybeT getStuffSometimes a
        lift $ getStuffAlways stuff
    return (firstPart, secondPart)
于 2013-08-02T21:46:12.890 回答