Haskell - “我如何使用”如果“声明在”中“阻止”?

时间:2011-05-07 12:02:53

标签: haskell

  

可能重复:
  Haskell “do nothing” IO, or if without else

在这些“简单”的行中出了点问题......

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

GHCi会投诉标识符,或者在我添加else do后不执行最后一行操作。

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

感谢。

1 个答案:

答案 0 :(得分:31)

Haskell中的

if必须始终有thenelse。所以这将有效:

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

等效地,您可以使用Control.Monad中的when

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
相关问题