A mystery involving putStrLn

最后都变了- 提交于 2019-12-02 10:13:05

问题


Why does the piece of code below produce the error parse error on input ‘putStrLn’?

main = do line <- fmap reverse getLine
   putStrLn $ "You said " ++ line ++ " backwards!"
   putStrLn $ "Yes, you said " ++ line ++ " backwards!"

<interactive>:11:4: error: parse error on input ‘putStrLn’

Also, why does the following piece of code produce the error parse error on input ‘let’?

main = do line <- getLine
  let line' = reverse line
  putStrLn $ "You said " ++ line' ++ " backwards!"
  putStrLn $ "Yes, you said " ++ line' ++ " backwards!"


 <interactive>:31:4: error: parse error on input ‘let’

回答1:


Both snippets have the same problem. If you put the first action of a do block on the same line as the do itself, you still have to indent the rest of the actions in the do block as far as the first one. Two choices to fix it:

main = do line <- fmap reverse getLine
          putStrLn $ "You said " ++ line ++ " backwards!"
          putStrLn $ "Yes, you said " ++ line ++ " backwards!"

or

main = do
   line <- fmap reverse getLine
   putStrLn $ "You said " ++ line ++ " backwards!"
   putStrLn $ "Yes, you said " ++ line ++ " backwards!"



回答2:


It also works when explicit separators are used throughout:

main = do { line <- fmap reverse getLine ;
   putStrLn $ "You said " ++ line ++ " backwards!" ;
   putStrLn $ "Yes, you said " ++ line ++ " backwards!" }

main = do { line <- getLine ;
   let { line' = reverse line } ;                     -- NB let's { }s
   putStrLn $ "You said " ++ line' ++ " backwards!" ;
   putStrLn $ "Yes, you said " ++ line' ++ " backwards!" }

This is not a substitute for the good indentation style, but an addition to it.



来源:https://stackoverflow.com/questions/54795600/a-mystery-involving-putstrln

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!