【问题标题】:Haskell - "How can I use "if" statement in "do" block properly? [duplicate]Haskell-“如何在“do”块中正确使用“if”语句? [重复]
【发布时间】:2011-05-07 12:02:52
【问题描述】:

可能重复:
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 后不执行最后一行操作。

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

谢谢。

【问题讨论】:

    标签: haskell conditional-statements do-notation


    【解决方案1】:

    Haskell 中的if 必须始终有一个then 和一个else。所以这会起作用:

    action = do
        isdir <- doesDirectoryExist path
        if not isdir
            then handleWrong
            else return ()     -- i.e. do nothing
        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
    

    【讨论】:

      猜你喜欢
      • 2021-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-06
      • 1970-01-01
      • 2019-12-04
      • 2015-02-16
      相关资源
      最近更新 更多