2011-05-07 6 views
9

Duplicar posible:?
Haskell “do nothing” IO, or if without elseHaskell - "¿Cómo puedo usar "if" en "do" bloque adecuadamente

Algo se equivocó en estas "líneas fáciles" .. .

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

GHCi se queja sobre identificadores, o no exec la última acción línea después agrego else do.

Creo que el manejo de excepciones puede funcionar, pero ¿es necesario en tales declaraciones comunes de "verificar y hacer algo"?

Gracias.

Respuesta

25

if en Haskell siempre debe tener un then y un else. Así que esto va a funcionar:

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

De manera equivalente, puede utilizar when de Control.Monad:

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

Control.Monad también tiene unless:

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

Tenga en cuenta que cuando usted intentó

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

se analiza como

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