In Haskell, an if-else expression does not mean "if true, execute foo; else, execute bar", but "if true, the value is foo; else, the value is bar". For that reason, you can't omit the else
, much in the same way that you can't when using the ternary if operator (conditon ? foo : bar
) in other languages. In your case, the then
part is a value of type IO ()
, so you need an else
with the same type. As you do not want antyhing to actually happen if the condition is false, the most immediate solution is using the dummy IO ()
value, return ()
:
palin :: IO ()
palin
= do line <- getLine
putStr line
if True
then putStr line
else return ()
You can also use the when
function from Control.Monad
, which has the same effect:
import Control.Monad
palin :: IO ()
palin
= do line <- getLine
putStr line
when True (putStr line)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…