尽早终止monadic fold

时间:2014-06-15 02:36:07

标签: haskell monads fold

我写过这篇文章是因为我可以提前终止monadic折叠:

myfoldM             :: (Monad m) => (a -> b -> m (Maybe a)) -> a -> [b] -> m (Maybe a)
myfoldM _ a []      =  return $ Just a
myfoldM f a (x:xs)  =  do ma <- f a x;
                          case ma of
                            Nothing -> return Nothing
                            Just a' -> myfoldM f a' xs

我想知道是否有更优雅的方式来表达这个或者库中是否存在类似的东西。当然,有一个类似的版本将Maybe替换为Either

更新......这是基于PetrPudlák的回答的完整解决方案:

import Control.Monad (foldM,Monad,mzero)
import Control.Monad.Trans.Maybe (MaybeT(..))
import Control.Monad.Trans.Class (lift)

myfoldM' :: (Monad m) => (a -> b -> MaybeT m a) -> a -> [b] -> m (Maybe a)
myfoldM' f = (runMaybeT .) . foldM f

go :: Int -> Int -> MaybeT IO Int
go s i = do
  lift $ putStrLn $ "i = " ++ show i
  if i <= 4 then return (s+i) else mzero

test n = do
  myfoldM' go 0 [1..n] >>= print      

-- test 3 => Just 6
-- test 5 => Nothing

1 个答案:

答案 0 :(得分:13)

这只是一个标准的monadic foldM,提前退出。这可以通过将内部计算包装到MaybeT

来完成
import Control.Monad
import Control.Monad.Trans.Error
import Control.Monad.Trans.Maybe

myfoldM :: (Monad m) => (a -> b -> m (Maybe a)) -> a -> [b] -> m (Maybe a)
myfoldM f = (runMaybeT .) . foldM ((MaybeT .) . f)

但我认为直接使用MaybeT给出折叠函数更方便,因为它可以轻松地通过mzero终止计算,而不是操纵Maybe值,在这种情况下,几乎不值得为它编写单独的函数:

myfoldM' :: (Monad m) => (a -> b -> MaybeT m a) -> a -> [b] -> m (Maybe a)
myfoldM' f = (runMaybeT .) . foldM f

Either来说,它是一样的:

myfoldM'' :: (Monad m, Error e)
          => (a -> b -> ErrorT e m a) -> a -> [b] -> m (Either e a)
myfoldM'' f = (runErrorT .) . foldM f