Haskell - “我如何使用”如果“在“do”中的语句正确阻止? [英] Haskell - "How can I use "if" statement in "do" block properly?

查看:101
本文介绍了Haskell - “我如何使用”如果“在“do”中的语句正确阻止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

Haskell什么也不做 IO,或者如果没有其他的话


这些简单行中出现错误...

  action = do 
isdir< - doesDirectoryExist路径 - 检查目录是否存在。
if(不是isdir)
然后处理错误
doOtherActions - 在这里编译错误。

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



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

谢谢。

解决方案

if 在Haskell中必须始终有一个,然后和一个 else 。因此,这将工作:

  action = do 
isdir< - doesDirectoryExist路径
如果不是isdir
then handleWrong
else return()
doOtherActions

等价地,你可以在Control.Monad 时使用

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

Control.Monad也有除非

  action = do 
isdir < - doesDirectoryExist path
除非isdir handleWrong
doOtherActions






请注意,当您尝试

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

它被解析为

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


Possible Duplicate:
Haskell “do nothing” IO, or if without else

Something got wrong in these "easy" lines ...

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

GHCi will complaint about identifiers , or do not exec the last line action after I add else do .

I think exception handling may work, but is it necessary in such common "check and do something" statements ?

Thanks.

解决方案

if in Haskell must always have a then and an else. So this will work:

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

Equivalently, you can use when from Control.Monad:

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

Control.Monad also has unless:

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


Note that when you tried

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

it was parsed as

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

这篇关于Haskell - “我如何使用”如果“在“do”中的语句正确阻止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆