在IO Monad中链接if / else语句

时间:2015-11-08 10:34:52

标签: haskell monads

我想知道是否有一种惯用的方法来编写类似于IO Monad中命令式语言中的链式if / else语句的控制代码。

所以在像Python这样的语言中,我通常会这样:

if οs.path.isdir(fname):
    # do whatever
elif os.path.isfile(fname):
    # ...
else:
    # ...

我能在Haskell中找到的最好成绩如下:

isf <- doesFileExist path
isd <- if isf then return False else doesDirectoryExist path
case (isf, isd) of
    (True,  _)      -> return ...
    (_,     True)   -> return ...
    _               -> return ...

哪个不太好,我想知道是否有更好的方式来编写这类东西。

另外,为了验证我的理解:如果您不想总是同时执行这两项操作,那么在IO Monad的情况下,if isf中的isd <- ...部分是必需的。我的猜测是在其他Monads(懒惰的Monads?)中,这不需要,因为isd会被懒惰地评估。

修改

根据第一条评论,我最终得到以下结论:

firstMatchM :: (Monad m) => a -> [(a -> m Bool, b)] -> b -> m b
firstMatchM arg [] def   = return def
firstMatchM arg ((check,x):xs) def = do
    t <- check arg
    if t then return x else firstMatchM arg xs def

doFirstM :: (Monad m) => a -> [(a -> m Bool, a -> m b)] -> (a -> m b) -> m b
doFirstM arg acts def = do
    fm <- firstMatchM arg acts def
    fm arg

handlePath2 path = doFirstM path
   [( \p -> doesFileExist p,
         \p ->  return "file"
   ),(\p -> doesDirectoryExist p,
         \p -> return "dir"
   )] $ \p -> return "Error"

这与@ chi的第二个建议类似,我更喜欢ifM,因为它更接近命令式版本。

1 个答案:

答案 0 :(得分:4)

如果我们不想让monad变形金刚参与其中,一个基本选择就是推出我们自己的monadic if

ifM :: Monad m => m Bool -> m a -> m a -> m a
ifM act t e = do
  b <- act
  if b then t else e

然后代码结构类似于命令式语言中的代码结构:

test :: IO String
test = ifM anAction (do
          putStrLn "branch a"
          return "a")
       $ ifM otherAction (do
          putStrLn "branch b"
          return "b")
       $ return "none"

其中anAction, otherAction :: IO Bool

或者,使用类似

的内容
ifChain :: [(IO Bool, IO a)] -> IO a -> IO a
ifChain [] e = e
ifChain ((g, a) : acts) e = do
   b <- g
   if b then a else ifChain acts e