涉及putStrLn的一个谜

A mystery involving putStrLn

为什么下面的代码会产生错误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’

另外,为什么下面这段代码会产生错误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’

两个片段都有同样的问题。如果您将 do 块的第一个动作与 do 本身放在同一行,您仍然必须将 do 块中的其余动作缩进到第一个一。两种修复方式:

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

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

当在整个过程中使用显式分隔符时,它也有效:

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!" }

这不是好的缩进样式的替代品,而是对其的补充。