2011-05-07 19 views
9

可能重複:
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將投訴有關標識符,或者我加後不執行的是最後一行的行動。

我認爲異常處理可能有效,但是在這種常見的「檢查和做某事」陳述中是否有必要?

謝謝。

回答

25

if在Haskell必須始終有一個then和一個else。因此,這將工作:

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