Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

haskell - Parse error on input 'if' when trying to use a condition inside a do block

I have the following code and I already tried multiple ways to write this, but I can't make it work. What I need is to use an if condition inside a do block.

palin :: IO ()
palin 
  = do line <- getLine
       putStr line
       if True
         then putStr line

I changed the condition to true just to make it easier. I tried adding the else sentence, but I get the same.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...