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

前端 未结 3 2068
被撕碎了的回忆
被撕碎了的回忆 2020-12-20 18:37

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

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-20 19:18

    In Haskell everything after = is an expression, and expressions usually have values. Even conditional statement is expression as well as putStr "hi" and they have their (return) values. In case of if return value is value of corresponding branch (then or else). In case of putStr "hi" it's somewhat more involved, I won't explain it here (see IO and monads)

    So the correct way to write your code would be the following:

    palin :: IO ()
    palin = do line <- getLine
               if True
                 then putStr line
                 else return ()
                 -- this return has nothing to do with return in python
                 -- basically it means "do nothing"
    

提交回复
热议问题