14

可能重复:
Haskell “什么都不做” IO,或者如果没有其他

这些“简单”的行出了点问题……

action = do
    isdir <- doesDirectoryExist path  -- check if directory exists.
    if(not isdir)                     
        then do handleWrong
    doOtherActions                    -- compiling ERROR here.

GHCi 将抱怨标识符,或者在我添加后不执行最后一行操作else do

我认为异常处理可能有效,但在这种常见的“检查并做某事”语句中是否有必要?

谢谢。

4

1 回答 1

33

if在 Haskell 中必须始终有 athen和 a else。所以这将起作用:

action = do
    isdir <- doesDirectoryExist path
    if not isdir
        then handleWrong
        else return ()     -- i.e. do nothing
    doOtherActions

等效地,您可以when从 Control.Monad 使用:

action = do
    isdir <- doesDirectoryExist path
    when (not isdir) handleWrong
    doOtherActions

Control.Monad 还有unless

action = do
    isdir <- doesDirectoryExist path
    unless isdir handleWrong
    doOtherActions

请注意,当您尝试

action = do
    isdir <- doesDirectoryExist path
    if(not isdir)
        then do handleWrong
        else do
    doOtherActions

它被解析为

action = do
    isdir <- doesDirectoryExist path
    if(not isdir)
        then do handleWrong
        else do doOtherActions
于 2011-05-07T12:30:07.287 回答